Dav*_*nte 11 arrays objective-c nspredicate ios
我有一个名称,地址,电话的对象数组.没有等
我希望能够在数组中搜索任何术语的出现 - 无论是在名称字段,地址字段等.
我有这样的想法:
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.searchResults removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchText];
searchResults = [NSMutableArray arrayWithArray:[contactArray filteredArrayUsingPredicate:predicate]];
}
Run Code Online (Sandbox Code Playgroud)
这会导致异常"无法在集合中使用/包含运算符".
UPDATE.我现在可以搜索最多三个字段.当我添加第四个(以任何顺序)时,我得到这个异常:"无法解析格式字符串......"
Predicate代码现在是:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.narrative contains[c] %@ OR SELF.category contains[c] %@ OR SELF.date contains[c] OR SELF.name contains[c] %@", searchText, searchText, searchText, searchText];
searchResults = [NSMutableArray arrayWithArray:[allDreams filteredArrayUsingPredicate:predicate]];
Run Code Online (Sandbox Code Playgroud)
三个谓词搜索字段的限制?我该如何解决这个问题?再次感谢.
Mon*_*olo 17
只需使用一个谓词字符串来检查它们:
@"name contains[cd] %@ OR address contains[cd] %@"
Run Code Online (Sandbox Code Playgroud)
你可以添加任意多个.
唯一的缺点是你需要为你想要测试的每个字段添加相同的搜索字符串,这看起来有点难看.
如果您的对象是字典,那么有一种方法可以使用子查询真正搜索所有值,而无需在编译时知道它们的名称.
它的工作原理如下:
@"subquery(self.@allValues, $av, $av contains %@).@count > 0"
Run Code Online (Sandbox Code Playgroud)
它使用@allValues
特殊键(或方法调用,如果您愿意)用于字典对象,并使用它来过滤包含搜索字符串的任何值.如果找到任何(即,计数为正),则对象包含在结果中.
请注意,这将不加选择地检查所有值,即使您在字典中有任何值也不想包含这些值.
归档时间: |
|
查看次数: |
23537 次 |
最近记录: |