gdm
gdm

Reputation: 7978

Associative quick find of NSDictionary as elements of NSArray

Suppose I have an NSMutableArray of NSDictionary like this (every row is a dictionary):

     key count type
 0    1   1     Apple
 1    1   2     Banana
 2    2   1     Pear
 3    3   4     Ananas

Suppose that I would find all fruits for key 1. The simple and brute way is enumerate the NSMutableArray and find only those NSDictionary which have as key = 1. There is a better or smarter way? (Data come from an SQL query).

Upvotes: 1

Views: 193

Answers (2)

Jitendra
Jitendra

Reputation: 5081

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

    NSLog(@"%@",filtered);

Try this one might be helpful to you..

Upvotes: 0

s1m0n
s1m0n

Reputation: 7685

You could try using the filteredArrayUsingPredicate: method of NSArray:

// Supposing originalArray is an NSArray holding the NSDictionaries that represent the fruits
NSArray *filteredArray = [originalArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"key == %@", @1]];

filteredArray will now hold all the dictionaries with 1 as key.

Upvotes: 3

Related Questions