Rye*_*AC3 1 core-data uisearchbar nspredicate ios
我正在尝试为我的核心数据搜索创建复合谓词.因此,当用户在搜索栏中输入文本时,它将显示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];
}
Run Code Online (Sandbox Code Playgroud)
但它只是在没有描述性原因的情况下崩溃.所以我认为我需要采用这三个谓词并以某种方式将它们组合在一起:
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];
Run Code Online (Sandbox Code Playgroud)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) || (optionOne contains[cd] %@) || (optionTwo contains[cd] %@)", self.sBar.text];
Run Code Online (Sandbox Code Playgroud)
由于%@字符串中有3个标记self.sBar.text,因此最后需要有3个表达式.
或者,您可以这样做:
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];
Run Code Online (Sandbox Code Playgroud)
如果你正在构建这个谓词,那么这很容易,因为你可以将"模板"谓词存储在一个ivar中.解析谓词并不是最快的事情,使用模板版本意味着您只需解析一次(而不是每次搜索栏的文本更改).
| 归档时间: |
|
| 查看次数: |
1656 次 |
| 最近记录: |