例如,我有一个具有三个属性的对象:firstName,middleName,lastName.
如果我想使用nspredicate在所有属性中搜索字符串“john”.
而不是像以下那样创建谓词:
[nspredicate predicateWithFormat:@“(firstName包含[cd]%@)OR(lastName包含[cd]%@)OR(middleName包含[cd]%@)”,@“john”,@“john “];
我可以这样做:
[nspredicate predicateWithFormat:@“(全部包含[cd]%@),@”john“];
解决方法
“all contains”在谓词中不起作用,并且(据我所知),没有类似的语法来获得所需的结果.
以下代码从实体中的所有“String”属性创建“复合谓词”:
Nsstring *searchText = @"john"; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedobjectContext:context]; NSMutableArray *subPredicates = [NSMutableArray array]; for (NSAttributeDescription *attr in [entity properties]) { if ([attr isKindOfClass:[NSAttributeDescription class]]) { if ([attr attributeType] == NsstringAttributeType) { nspredicate *tmp = [nspredicate predicateWithFormat:@"%K CONTAINS[cd] %@",[attr name],searchText]; [subPredicates addobject:tmp]; } } } nspredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; NSLog(@"%@",predicate); // firstName CONTAINS[cd] "john" OR lastName CONTAINS[cd] "john" OR middleName CONTAINS[cd] "john"