Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

containsObject:

Returns a Boolean value that indicates whether a given object is present in the array.

  • (BOOL)containsObject:(id)anObject Parameters anObject An object.

Return Value YES if anObject is present in the array, otherwise NO.

Discussion

This method determines whether anObject is present in the array by sending an isEqual: message to each of the array’s objects (and passing anObject as the parameter to each isEqual: message).

Declared In

NSArray.h

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top