如何创建一个比较对象的所有属性的谓词?

Dav*_*Liu 7 key-value-coding nspredicate ios

例如,我有一个具有三个属性的对象:firstName,middleName,lastName.

如果我想使用NSPredicate在所有属性中搜索字符串"john".

而不是像以下那样创建谓词:

[NSPredicate predicateWithFormat:@"(firstName contains[cd] %@) OR (lastName contains[cd] %@) OR (middleName contains[cd] %@)", @"john", @"john", @"john"];

我可以这样做:

[NSPredicate predicateWithFormat:@"(all contains[cd] %@), @"john"];

Mar*_*n R 4

“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"
Run Code Online (Sandbox Code Playgroud)

  • @AbidHussain:是的,但是枚举属性也会给出从 NSManagedObject 或 NSObject 继承的所有属性。此方法仅提供为实体定义的属性。 (2认同)