【问题标题】:Trying to make a compond predicate. Not working.试图做一个复合谓词。不工作。
【发布时间】:2011-06-17 18:00:12
【问题描述】:

我正在尝试为我的核心数据搜索创建一个复合谓词。因此,当用户在搜索栏中输入文本时,它将显示在 name、optionOne 或 optionTwo 属性中包含该文本的任何内容的结果。

我试过了:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (self.sBar.text !=nil)   {

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) || (optionOne contains[cd] %@) || (optionTwo contains[cd] %@)", self.sBar.text];

        [fetchedResultsController.fetchRequest setPredicate:predicate];

    }

    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        // Handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }           

    [self.myTable reloadData];

    [sBar resignFirstResponder];  

}

但它只是在没有描述性原因的情况下崩溃。所以我想我需要把这三个谓词结合起来:

NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", self.sBar.text];

NSPredicate *optionOnePredicate = [NSPredicate predicateWithFormat:@"optionOne contains[cd] %@", self.sBar.text];

NSPredicate *optionTwoPredicate = [NSPredicate predicateWithFormat:@"optionTwo contains[cd] %@", self.sBar.text];

【问题讨论】:

    标签: ios core-data uisearchbar nspredicate


    【解决方案1】:
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) || (optionOne contains[cd] %@) || (optionTwo contains[cd] %@)", self.sBar.text];
    

    由于您的字符串中有 3 个 %@ 标记,因此您需要在末尾有 3 个 self.sBar.text 表达式。

    或者,您可以这样做:

    NSPredicate *template = [NSPredicate predicateWithFormat:@"name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH OR optionTwo contains[cd] $SEARCH"];
    NSDictionary *replace = [NSDictionary dictionaryWithObject:self.sBar.text forKey:@"SEARCH"];
    NSPredicate *predicate = [template predicateWithSubstitutionVariables:replace];
    

    如果您经常构建此谓词,这会更方便,因为您可以将“模板”谓词存储在 ivar 中。解析谓词并不是最简单的事情,使用模板版本意味着您只需解析一次(而不是每次搜索栏的文本更改时)。

    【讨论】:

    • 嗯,报错“'Unable to parse the format string "name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH optionTwo contains[cd] $SEARCH"'”和第二个部分。第一部分工作得很好。谢谢。
    • @RyeMAC3 哎呀,我忘了OR
    • 伙计,不敢相信我没看到!再次感谢。
    猜你喜欢
    • 2022-01-06
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    相关资源
    最近更新 更多