views:

594

answers:

2

This feels like such a stupid question, but how can I find a string in an NSArray?

I tried using

[array indexOfObjectIdenticalTo:myString]

but that requires the sting to have the same address.

Does anyone have any tips on how to do this?

+14  A: 

You want the indexOfObject: method, which looks for the object by sending each object in the array an isEqual: message.

Peter Hosey
+7  A: 

Peter's answer is correct.

One additional note; if you have tons and tons of strings in the array, -indexOfObject: is going to do a linear search. This may prove to be a performance bottleneck for which you should consider using a different container; an NSSet or NSDictionary, possibly (depending on what the strings mean).

Another gotcha is if the strings are all relatively similar and/or relatively long.

Of course, don't bother optimizing anything until you have used the analysis tools to prove that you have a performance issue.

bbum