views:

1083

answers:

3

I have two arrays in Objective C and I need to find what index something is so I can insert it in the same place. For instance, lets say I have a "name array" and an "age array". How do I find out what index "charlie" is in the "name array" so I know where to insert his age in the "age" array?

Thanks

+3  A: 

-[NSArray indexOfObject:] would seem to be the logical choice.

Chuck
Yes it would chuck, thanks I couldn't find that in the NSMutableArray class reference.
Xcoder
Yep, the NSMutableArray docs only contain methods that have to do with mutating arrays. It's always worthwhile to check out the superclass docs as well.
Chuck
+2  A: 

You might just want to use an NSDictionary, too, if you're doing lookups based on strings.

John
That's a great point. People often overlook the fact that searching an array for a given string takes linear time, while searching for a string in a dictionary takes constant time. Chuck is correct about how to do it for arrays, but based on the sparse description, a dictionary seems like a great potential solution.
Quinn Taylor
Even so, it's worth remembering that linear time can be faster than constant time if the constant is large or the line short. Basically, don't worry about it until you've confirmed by measuring that it really is a performance problem.
Peter Hosey
+2  A: 

In Cocoa, parallel arrays are a path to doom and ruination. You can't use them effectively with Bindings, so you'll have to write a lot of glue code instead, as if Bindings didn't exist. Moreover, you're killing off any future AppleScript/Scripting Bridge support you may intend to have before you even begin to implement it.

The correct way is to create a model class with name and age properties, and have a single array of instances of that class. Then, to find an item by name or age, use NSPredicate to filter the array, and indexOfObjectIdenticalTo: to find the index of each item from the filtered array in the main array.

The difference between indexOfObject: and indexOfObjectIdenticalTo: is that the former will send isEqual: messages to determine whether each object is the one it's looking for, whereas the latter will only look for the specific object you passed in. Thus, you can use indexOfObject: with an object that isn't in the array but is equal to one that is, in order to find the equal object in the array.

Peter Hosey