例如,我有像@{@"firstName":@"aaa", @"lastName":@"bbb"}
这样的对象。
现在我尝试使用下一个谓词进行搜索:
NSPredicate *predicateFirstName = [NSPredicate predicateWithFormat:@"firstName contains [c] %@", searchString];
NSPredicate *predicateLastName = [NSPredicate predicateWithFormat:@"lastName contains [c] %@", searchString];
NSPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateFirstName, predicateLastName]];
searchUsersArray = [usersArray filteredArrayUsingPredicate:orPredicate];
我需要一个谓词,它将返回搜索字符串@" aa bb"名字ENDED with" aa"和lastName BEGINS与@" bb"
NSPredicate *predicateLastName = [NSPredicate predicateWithFormat:@"(firstName AND lastName contains [c] %@)", searchString]
不能为我工作。
答案 0 :(得分:1)
首先将搜索字符串分成末尾部分和开始部分:
NSArray *parts = [@"aa bb" componentsSeperatedByString:@" "];
然后使用BEGINSWITH
和ENDSWITH
:
[NSPredicate predicateWithFormat:@"(firstName ENDSWITH[c] %@) AND (lastName BEGINSWITH[c] %@", parts[0], parts[1]];
或者,您可以将计算属性添加到实体,并将名字和姓氏结合起来,然后在此属性中搜索。
答案 1 :(得分:1)
尝试这样希望它可以帮助你
NSString *matchString = [NSString stringWithFormat: @"(.*aa|bb.*)",searchText];
NSString *predicateString = @"keyword MATCHES[c] %@";
NSPredicate *predicate =[NSPredicate predicateWithFormat: predicateString, matchString];
由于
答案 2 :(得分:0)
使用关键字BEGINSWITH而不是包含。
NSPredicate *predicateFirstName = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH [c] %@", searchString];
NSPredicate *predicateLastName = [NSPredicate predicateWithFormat:@"lastName BEGINSWITH [c] %@", searchString];