如何创建一个比较对象所有属性的谓词?
例如,我有一个有三个属性的对象: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"];
“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"
你可以这样做,
NSMutableArray *allTheContaint = [[NSMutableArray alloc] init];
[allTheContaint addObject:allTheContaint.firstName];
[allTheContaint addObject:allTheContaint.middleName];
[allTheContaint addObject:allTheContaint.lastName];
NSPredicate *predicateProduct = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", @"john"];
NSArray *filteredArray = [self.listOfProducts filteredArrayUsingPredicate:predicateProduct];
NSLog(@"%@", filteredArray);
但它是修复。 :(不适合动态:)
链接地址: http://www.djcxy.com/p/78675.html上一篇: How to create a predicate that compares all properties of an object?