12

I have an NSArray of NSDictionary objects. I want to filter the array based on keys of the dictionaries using NSPredicate. I have been doing something like this:

NSString *predicateString = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];

This works fine if they key passed in is one-word: Color, Name, Age. But it doesn't work if the key is multi-word, like: Person Age, Person Name.

Basically, any key that contains a space, it doesn't work. I have tried putting single quotes around the key in the string, just like they are done on the value side but that didn't work either. Also tried double quotes, but to no avail.

Please advise on this. Thanks in advance.

Duck
  • 34,902
  • 47
  • 248
  • 470
Bittu
  • 676
  • 2
  • 8
  • 22

2 Answers2

23

For me, Kevin's answer did not work. I used:

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself
        NSLog(@"predicate %@",predicateString);
        filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];
NightFury
  • 13,436
  • 6
  • 71
  • 120
16

When using a dynamic key, you should use the %K token instead of %@. You also don't want the quotes around the value token. They will cause your predicate to test for equality against the literal string @"%@" instead of against value.

NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];

This is documented in the Predicate Format String Syntax guide.


Edit: As Anum Amin points out, +[NSString stringWithFormat:] doesn't handle predicate formats. You want [NSPredicate predicateWithFormat:@"%K == %@", key, value] instead.

commanda
  • 4,841
  • 1
  • 25
  • 34
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 5
    NSString will not substitute %K correctly. One should use `[NSPredicate predicateWithFormat:]`. See my answer below. – NightFury Dec 18 '12 at 05:11
  • @AnumAmin: You're absolutely right. I suppose that's what I get for trying to "fix" Bittu's code instead of creating it fresh. I'm surprised he even accepted my answer as-is. – Lily Ballard Dec 18 '12 at 09:33
  • I was already using NSPredicate predicateWithFormat: so, it was easy to do it in that statement instead of a separate statement for creating a NSString. I should have clarified it in a comment but Anum did it well :) – Bittu Jan 04 '13 at 22:38