Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSPredicate to filter an NSArray based on NSDictionary keys

I have an array of dictionaries.

I want to filter the array based on a key.

I tried this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  %@)", @"Football"];  NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate]; 

This doesn't work, I get no results. I think I'm doing something wrong. I know this is the method if "SPORT" was an ivar. I think it is probably different if it is a key.

I haven't been able to find an example however.

Thanks


Update

I added quotes around the string I am searching for.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  '%@')", @"Football"]; 

It still does not work.


Update 2

Solved it. I actually had to remove the single quotes, which seems to go against what the guide says.

My real problem is I had a nested array and I wasn't actually evaluating the dictionaries. Bone head move.

like image 447
Corey Floyd Avatar asked Jun 06 '09 00:06

Corey Floyd


2 Answers

It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];     NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]]; 

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

like image 105
suraken Avatar answered Oct 10 '22 07:10

suraken


I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.

From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.

like image 44
ChargedNeuron Avatar answered Oct 10 '22 07:10

ChargedNeuron