例如,我有一个具有三个属性的对象: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"