11

我在 CoreData 中有一组用户,在我的应用程序中有一个搜索字段。用户具有属性 firstname 和 name。

目前我有一个谓词,如“user.name CONTAINS[c] %@ OR user.firstname CONTAINS[c] %@”

这一直有效,直到用户键入像“john smith”这样的全名。即使他键入“john sm”,也应该找到 John Smith-Object。

将搜索词数组 (IN) 与 CONTAINS 组合的谓词是什么?

4

4 回答 4

38

我认为您不能在谓词中将“IN”与“CONTAINS”结合起来。但是您可以将搜索字符串拆分为单词,并创建一个“复合谓词”:

NSString *searchString = @"John  Sm ";
NSArray *words = [searchString componentsSeparatedByString:@" "];
NSMutableArray *predicateList = [NSMutableArray array];
for (NSString *word in words) {
    if ([word length] > 0) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"user.name CONTAINS[c] %@ OR user.firstname CONTAINS[c] %@", word, word];
        [predicateList addObject:pred];
    }
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateList];
NSLog(@"%@", predicate);

此示例生成谓词

(user.name CONTAINS[c] "John" OR user.firstname CONTAINS[c] "John") AND
(user.name CONTAINS[c] "Sm" OR user.firstname CONTAINS[c] "Sm")

这将匹配“约翰史密斯”,但不匹配“约翰米勒”。

于 2012-11-20T20:21:54.747 回答
15

2.5 年后,我可以用 swift 中更复杂的示例来回答我的问题:

var predicateList = [NSPredicate]()

let words = filterText.componentsSeparatedByString(" ")

for word in words{

     if count(word)==0{
           continue
     }

     let firstNamePredicate = NSPredicate(format: "firstName contains[c] %@", word)
     let lastNamePredicate = NSPredicate(format: "lastName contains[c] %@", word)
     let departmentPredicate = NSPredicate(format: "department contains[c] %@", word)
     let jobTitlePredicate = NSPredicate(format: "jobTitle contains[c] %@", word)

     let orCompoundPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [firstNamePredicate, lastNamePredicate,departmentPredicate,jobTitlePredicate])

     predicateList.append(orCompoundPredicate)
}

request.predicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: predicateList)
于 2015-05-25T17:55:29.790 回答
4

斯威夫特 4 更新:

let firstName = NSPredicate(format: "firstName CONTAINS[c] %@", searchText)
let lastName = NSPredicate(format: "lastName CONTAINS[c] %@", searchText)

let orCompoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: 
[firstNamePredicate,lastNamePredicate]

在获取数据时使用orCompoundPredicate 。

于 2018-02-24T13:20:10.343 回答
-1

我遇到了同样的问题并像这样解决了它:

在我的 NSManagedObject 类(用户)中,我添加了以下方法,将两个值合并为一个字符串:

- (NSString *)name
{
    return [NSString stringWithFormat:@"%@ %@", self.firstname, self.lastname];
}

然后你只需要以下几行来匹配你的列表,在我的例子中是一个带有用户对象的 NSArray:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchString];
NSArray *filteredUsers = [users filteredArrayUsingPredicate:predicate];
于 2012-11-28T19:32:33.597 回答