What is the best way to create this line? (NSMutableString ...)

I have a dictionary whose keys are NSStrings and whose NSArray objects. Here is an example:

key (NSString) : GroupA 
value (NSArray): John
                 Alex
                 Joe
                 Bob

There are many such entries, this is just an example. I need to create a line like this (for example:

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

I am going to feed this line to NSPredicate. What is the best way to create this line? I can use for loops, and if all that, but is there a more elegant way? Thank.

+3
source share
2 answers

This is not a valid predicate format string, so even if you finish generating it, you cannot convert it to NSPredicate

Here you want instead:

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];
+5

-

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);
+1

All Articles