【问题标题】:Searching an Array using NSPredicate method predicateWithFormat使用 NSPredicate 方法 predicateWithFormat 搜索数组
【发布时间】:2013-09-07 19:27:45
【问题描述】:

当前尝试设置搜索将搜索如下所示的数组 (bakeryProductArray)

“茶饼”, 提拉穆苏, “糖浆面包”, 琐事, “三重巧克力布朗尼”, 松露, “各种海绵”, “维也纳漩涡”, “婚礼蛋糕”

用户在 UISearchbar 中键入的内容。我不清楚如何在 CFString 中表示数组中的每个项目。

我目前拥有的代码是。

-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{

    searchSearch = [NSPredicate predicateWithFormat:@"self CONTAINS[cd]",searchText];
    //@"%K CONTAINS[cd] %@"
    searchResults = [bakeryProductArray filteredArrayUsingPredicate:searchSearch];

    NSLog(@"Filtered Food Product Count --> %d",[searchResults count]);
}

可以回答任何问题并在需要时提供更多代码。

【问题讨论】:

    标签: ios objective-c nsarray nspredicate


    【解决方案1】:

    这是你要找的吗?

    NSArray *bakeryProductArray = @[@"Tea Loaf", @"Tiramusu", @"Treacle Loaf", @"Trifle"];
    NSString *searchText = @"tr";
    
    NSPredicate *searchSearch = [NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", searchText];
    NSArray *searchResults = [bakeryProductArray filteredArrayUsingPredicate:searchSearch];
    
    NSLog(@"%@", searchResults);
    // "Treacle Loaf",
    // Trifle
    

    这会查找所有包含给定搜索字符串的字符串(不区分大小写)。 或者,您可以根据需要使用“=”或“BEGINSWITH”。 (有关"Predicate Programming Guide" 中的谓词的更多信息。)

    【讨论】:

    • 那几行的东西。该数组是从外部数据源创建的。 searchText 是方法调用的一部分。将更新问题中的代码。
    • @Evilelement:现在我不明白这个问题了。究竟是什么不工作?你得到什么结果,你期望什么?
    • 忽略“那些线上的东西”:D 基本上希望用户能够搜索面包店数组(结果缩小)。
    • @Evilelement:但是您的代码应该这样做。问题出在哪里?
    • 由于未捕获的异常'NSInvalidArgumentException',它会生成错误***终止应用程序,原因:'无法解析格式字符串“self CONTAINS[cd]”'
    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多