Reputation: 1
I have array of NSDictionaries
, in which i have to check if a dictionary with a certain key is exist, and it should be as fast as possible (done many times in real time )
To check if dic has key you have :
BOOL contains = [[dictionary allKeys] containsObject:obj];
or if([ dic objecetForKey:@"key"] != nil )
but to check the full array i have to run on all its objects ?
e.g
bool is=0;
for(nsdictionary *dic in array)
if([ dic objecetForKey:@"key"] != nil )
is=1;
//is says if i have the dic .
Upvotes: 2
Views: 4692
Reputation: 1252
Another way:
Using NSPredicates
NSPredicate *applePred = [NSPredicate predicateWithFormat:
@"employer.name == 'Apple'"];
NSArray *appleEmployees = [people filteredArrayUsingPredicate:applePred];
or Using Blocks
- (BOOL)personExists:(NSString *)key withValue:(NSString *)value {
NSPredicate *predExists = [NSPredicate predicateWithFormat:
@"%K MATCHES[c] %@", key, value];
NSUInteger index = [self.people indexOfObjectPassingTest:
^(id obj, NSUInteger idx, BOOL *stop) {
return [predExists evaluateWithObject:obj];
}];
if (index == NSNotFound) {
return NO;
}
return YES;
}
[myArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [obj someTestForValue: value];
}];
tutorial: http://useyourloaf.com/blog/2010/10/19/searching-arrays-with-nspredicate-and-blocks.html
Upvotes: 0
Reputation: 50089
KVC would look nice
NSArray *keys = [array valueForKeyPath:@"key"];
if([keys containsObject:@"myvalue"]) {
NSLog(@"nice");
}
Upvotes: 9
Reputation: 14865
Your approach is good, but I would insert a break statement, because no further search is required if you have already found a dictionary.
bool is = NO;
for(NSDictionary *dic in array){
if([dic objecetForKey:@"key"] != nil){
is = YES;
break;
}
}
Upvotes: 1