So I have an NSMutableArray in my app what is filled like so:
NSMutableArray
--Object 1 (NSMutableDictonary)
--Value (i) for key (key)
--Value (i) for key (key)
--Object 2 (NSMutableDictonary)
--Value (i) for key (key)
--Value (i) for key (key)
i need to be able to select an object from within the main NSMutableArray by looking for a key what matches a value of one of the NSMutableDictonary‘s keys…
I understand i could run a loop like so to achieve this:
for (NSMutableDictionary *object in arrayObject) {
if ([[object objectForKey:@"keyToSearch"] integerValue] == keyToCompare) {
return [object objectForKey:@"keyToReturn"];
}
}
However my concern is that if this array grows (what it can do) then this will take time to run a search on it..
So I was wondering is there any other way to retrieve the same results but more efficiently?
Thanks
Liam
The search is obviously going to take linear time in the number of dictionaries in the array. You’re not going to get around that by using a different way to search. You could rewrite your search to use an
NSPredicate, and it would be slightly shorter but it wouldn’t be any faster.If you want to make the search faster, you’ll have to modify your data structure. Or, you could create a
NSDictionaryto serve as a lookup table, where the keys of theNSDictionaryare values ofkeyToSearch, and the values are theNSMutableDictionariesin your array.Still, unless your array gets really really, big the search time will be negligible, and you shouldn’t worry about it.