views:

67

answers:

1

I have NSArray consisting of NSDictionary objects. Need to find index in NSArray of object with matching key name in NSDictionary. Dictionary has only 1 element. What is the fastest way of doing that? Filter with predicate and then use indexOfObject?

A: 

That method would certainly work, but if you're looking for speed, you need to change your structure. Arrays aren't meant to be searched this way. However, it's what NSDictionary was built for. If you have a unique key you're searching for, why not store your dictionaries in an NSDictionary and use the much, much faster objectForKey: method?

If you also need to maintain an ordering, you could create a custom "ordered dictionary" class using an NSMutableArray of the keys in your dictionary.

andyvn22
I don't really imagine how to use `objectForKey` in case I have single `NSDictionary` objects in parent `NSDictionary`. Say I convert my `NSArray` to `NSDictionary`, then the parent keys will be indexes containing dictionary elements with some keys I have to search! So it's like this `0=>[key1=>val1], 1=>[key2=>val2], N=>[keyM=>valM], etc..`. Given by `keyM` I want to know the `N`. I'm not sure even how to build a predicate to access dictionary, so can't build my own version ^^
Michael
I was suggesting you use the keys (your `key1`, `key2`, and so on) as the parent dictionary's keys, not use the would-be indices as the parent dictionary's keys. If your ordering is important and speed isn't an issue, just go with your original plan.
andyvn22