views:

3202

answers:

4

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.

A: 

Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football) You want it to read (SPORT == 'Football'), so your format string needs to be @"(SPORT == '%@')".

Martin Gordon
I thought thats what it said, too. Apparently the quotes aren't needed. I'm not sure exactly what the guide is saying quotes "should" be used for.
Corey Floyd
+4  A: 

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.)

suraken
You are right it should have worked, I was a bone head.
Corey Floyd
Does NSPredicate work on the iPhone? It works great on the sim but running it on the iPhone gives an error that the NSPredicate class could not be found.
lostInTransit
thank you......
Sijo
A: 

NSPredicate is only available in iPhone 3.0.

You won't notice that until try to run on device.

Rod
A: 

Just to mention that the predicate is case sensitive by default (use [c] to get unsensitive).

groumpf