我有一个字典,其键是NSStrings,其对象是NSArray。这是一个例子:
key (NSString) : GroupA
value (NSArray): John
Alex
Joe
Bob
有很多这样的条目,这只是一个例子。我需要做的是生成这样的字符串(例如:
(GroupA contains[cd] ('John' OR 'Alex' OR 'Joe' OR 'Bob')) AND (GroupB contains[cd] ('Starcraft' OR 'WOW' OR 'Warcraft' OR 'Diablo')) AND .....
我将把这个字符串提供给NSPredicate。生成此字符串的最佳方法是什么?我可以使用for循环,如果和所有这些,但是有更优雅的方式吗? 感谢。
答案 0 :(得分: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];
这不具有你原来所暗示的案例和变音不敏感性。如果你确实需要,那么你需要更复杂一点:
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];
答案 1 :(得分:1)
它应该是这样的
NSDictionary *myDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:@"John",@"Alex",@"Joe",@"Bob",nil] forKey:@"GroupA"];
NSString *myString = @"(";
int j = 0;
for(NSString *key in [myDict allKeys]) {
NSString *value = [myDict valueForKey:key];
myString = [myString stringByAppendingFormat:@"%@ contains[cd] (", key];
NSArray *myArray = (NSArray *)value;
int idx = 0;
for(NSString *name in myArray) {
myString = [myString stringByAppendingFormat:@"'%@'",name];
if(idx < [myArray count] - 1) {
myString = [myString stringByAppendingFormat:@" OR "];
}
idx++;
}
myString = [myString stringByAppendingString:@")"];
if(j < [myDict count] -1) {
myString = [myString stringByAppendingString:@" AND "];
}
j++;
};
myString = [myString stringByAppendingString:@")"];
NSLog(@"mystring %@",myString);