Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a string in an NSArray?

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?

like image 838
gargantuan Avatar asked Nov 28 '09 17:11

gargantuan


3 Answers

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

like image 75
Peter Hosey Avatar answered Nov 09 '22 21:11

Peter Hosey


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.

like image 32
bbum Avatar answered Nov 09 '22 22:11

bbum


You can use NSOrderSet as the container, the over view in NSOrderedSet Class Reference is below:

NSOrderedSet and its subclass, NSMutableOrderedSet, declare the programmatic interfaces to an ordered collection of objects.

NSOrderedSet declares the programmatic interface for static sets of distinct objects. You >establish a static set’s entries when it’s created, and thereafter the entries can’t be >modified. NSMutableOrderedSet, on the other hand, declares a programmatic interface for >dynamic sets of distinct objects. A dynamic—or mutable—set allows the addition and deletion >of entries at any time, automatically allocating memory as needed.

You can use ordered sets as an alternative to arrays when the order of elements is important >and performance in testing whether an object is contained in the set is a consideration— >testing for membership of an array is slower than testing for membership of a set.

Visit http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html

like image 4
6 1 Avatar answered Nov 09 '22 22:11

6 1