lag*_*gos 4 core-data nsstring nspredicate ios
我必须NSPredicate用于搜索一些Core Data对象.但是name自定义对象的键可以包含数字和字母.字符串可能看起来像:John 1234 Lennon或Ringo Starr.我通常会使用谓词NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",searchString];
但是,如果我搜索John Lennon谓词不返回任何内容,因为它无法比较它是否包含字符John Lennon,因为它缺少了1234.任何提示我可以使用什么样的谓词?
War*_*ton 12
您可以标记您的查询,也许就像这样简单
NSArray *tokens = [querystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Run Code Online (Sandbox Code Playgroud)
然后构造一个复合谓词.
NSMutableArray *predarray = [NSMutableArray array];
for(NSString *token in tokens)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",token];
[predarray addObject:predicate];
}
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:predarray];
Run Code Online (Sandbox Code Playgroud)
并将其提供给您的查询
在现实生活中,我会对每个令牌进行一些验证,以检查它是否会产生有效的谓词并且不会崩溃或产生安全风险.例如剥去像"*[]"这样的特殊字符
编辑:更正谓词类型以处理问题情况.
| 归档时间: |
|
| 查看次数: |
9816 次 |
| 最近记录: |