1

我有这个谓词:

NSPredicate * thePredicateKeyword = [NSPredicate predicateWithFormat:@"any keywords.thekeyword beginswith [cd] %@", searchTerm];

基本上每个企业都与关键字有多对多的关系。

但假设我没有一个 searchTerm。假设我有一个数组。

我该怎么做?

我想我可以为每个做谓词并将它们与或谓词等结合起来。

但是,有没有办法使用in关键字或类似的东西更有效地做到这一点?

4

2 回答 2

3

一个返回如下内容的函数呢:

-(NSPredicate *)createCompoundPredicateForSearchTerms:(NSArray *)searchTerms
{
  NSMutableArray *subPredicates = [[NSMutableArray alloc] init];

  NSEnumerator *searchTermEnum = [searchTerms objectEnumerator];
  NSString *searchTerm;
  while (searchTerm = [searchTermEnum nextObject]) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keywords.thekeyword beginswith [cd] %@", searchTerm];
    [subPredicates addObject:predicate];
  }

  return [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
}
于 2012-10-30T06:32:54.317 回答
0

这是我实际使用的。然而,我选择的答案是激发它的灵感。

NSArray * keywords = [searchTerm componentsSeparatedByString:@" "];

NSMutableArray * keywordPredicates = [NSMutableArray array];

for (NSString * aKeyword in keywords) {
    NSPredicate * thePredicateKeyword = [NSPredicate predicateWithFormat:@"any keywords.thekeyword beginswith [cd] %@", aKeyword];
    [keywordPredicates addObject:thePredicateKeyword];
}

NSPredicate * thePredicateKeyword = [NSCompoundPredicate orPredicateWithSubpredicates:keywordPredicates];

return thePredicateKeyword;
于 2012-10-31T03:55:59.727 回答