生成此字符串的最佳方法是什么?(...的NSMutableString)

use*_*064 3 cocoa-touch objective-c nspredicate nsmutablestring ios

我有一个字典,其键是NSStrings,其对象是NSArray.这是一个例子:

key (NSString) : GroupA 
value (NSArray): John
                 Alex
                 Joe
                 Bob
Run Code Online (Sandbox Code Playgroud)

有很多像这样的条目,这只是一个例子.我需要做的是生成这样的字符串(例如:

(GroupA contains[cd] ('John' OR 'Alex' OR 'Joe' OR 'Bob')) AND (GroupB contains[cd] ('Starcraft' OR 'WOW' OR 'Warcraft' OR 'Diablo')) AND ..... 
Run Code Online (Sandbox Code Playgroud)

我将把这个字符串提供给NSPredicate.生成此字符串的最佳方法是什么?我可以使用for循环,如果和所有这些,但是有更优雅的方式吗?谢谢.

Dav*_*ong 5

这不是一个有效的谓词格式字符串,所以即使你最终生成它,你也无法将其转换为 NSPredicate

这就是你想要的:

NSDictionary *groupValuePairs = ....;

NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *group in groupValuePairs) {
  NSArray *values = [groupValuePairs objectForKey:group];
  NSPredicate *p = [NSPredicate predicateWithFormat:@"%K IN %@", group, values];
  [subpredicates addObject:p];
}

NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
Run Code Online (Sandbox Code Playgroud)

这不具有原始暗示的案例和变音不敏感性.如果你真的需要它,那么你将需要更复杂一些:

NSDictionary *groupValuePairs = ....;

NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *group in groupValuePairs) {
  NSArray *values = [groupValuePairs objectForKey:group];
  NSMutableArray *groupSubpredicates = [NSMutableArray array];
  for (NSString *value in values) {
      NSPredicate *p = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", group, value];
      [groupSubpredicates addObject:p];
  }
  NSPredicate *p = [NSCompoundPredicate orPredicateWithSubpredicates:groupSubpredicates];
  [subpredicates addObject:p];
}

NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
Run Code Online (Sandbox Code Playgroud)