Jef Jef - 1 year ago 98
Objective-C Question

Better alternative for checking existence of NSDictionary's key in NSArray?

I have an NSArray of NSDictionaries. I need to check if there's at least one occurrence of an object for a key of the NSDictionary in the NSArray. I do this by using

int i;
for (i=0;i< [myArray count];i++)
if ([[[myArray objectAtIndex: i] objectForKey: myKey] isEqualToString: myString]) {
found = YES;
} else {
found = NO;

But I have a suspicion that there's a better/faster alternative for it...


Answer Source

This is as fast as you can get it with your current data structures. You're doing an O(1) lookup for each dictionary in the array. If you have a huge number of dictionaries, this might get expensive, so you could consider (depending very much on the semantics of your data) keeping a separate lookaside NSSet that contains the set of string objects comprising all the values in the dictionaries. Then you can check once in that set for existence.

Tell us more about the form of the data for more insight...

Also be careful with the == operator with NSStrings. If you're actually checking to see whether the text of the string is equal, you should use -isEqualToString: instead, as your form will just do a reference comparison.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download