比较NSPredicate的两个组件

时间:2014-09-05 13:18:28

标签: ios objective-c nspredicate

我想使用NSDictionary查询NSPredicate个联系人。我可以分别使用“firstName”和“lastName”搜索联系人,但我还需要搜索输入完整名称的联系人。

例如:如果我想搜索名为“John Doe”的联系人,并通过输入搜索关键字“John”或“Doe”进行搜索,我可以获得该名称,但我也希望它是当我输入搜索键“John Doe”时可搜索。目前我正在使用:

NSPredicate *p1 = [NSPredicate predicateWithFormat:@"lastNames BEGINSWITH[cd] %@", searchText];
NSArray *p1FilteredArray = [allContacts filteredArrayUsingPredicate:p1];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"firstNames BEGINSWITH[cd] %@", searchText];
NSArray *p2FilteredArray = [allContacts filteredArrayUsingPredicate:p2];
searchedArray = [[p1FilteredArray arrayByAddingObjectsFromArray:p2FilteredArray] mutableCopy];

2 个答案:

答案 0 :(得分:1)

您可以将单谓词与or运算符一起使用:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstNames beginswith[cd] %@ or lastNames beginswith[cd] %@", searchTerm, searchTerm];

NSArray *results = [allContacts filteredArrayUsingPredicate:predicate];

答案 1 :(得分:0)

我会做一些像这样:

NSArray *_allContacts = // ...;
NSString *_searchText = // ...;
NSArray *_result = [_allContacts filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
    return ([[[evaluatedObject valueForKey:@"lastNames"] lowercaseString] hasPrefix:[_searchText lowercaseString]] || [[[evaluatedObject valueForKey:@"firstNames"] lowercaseString] hasPrefix:[_searchText lowercaseString]]);
}]];