17

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 Answers 3

38

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

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it would chuck, thanks I couldn't find that in the NSMutableArray class reference.
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.
The docs make it easy to forget to check inherited methods, ivars and properties. Get yourself a copy of AppKiDo app by Andy Lee and it will be easier to see what you might be missing. Some classes are easier to understand when you see them in a new light.
6

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.

Comments

4

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

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.