问题
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
回答1:
-[NSArray indexOfObject:] would seem to be the logical choice.
回答2:
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.
回答3:
You might just want to use an NSDictionary, too, if you're doing lookups based on strings.
来源:https://stackoverflow.com/questions/1135075/how-to-determine-an-array-index-in-objective-c