How to find a string in an NSArray?

20,419

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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

Share:
20,419
gargantuan
Author by

gargantuan

Designer developer, living and working in London UK.

Updated on July 09, 2022

Comments

  • gargantuan
    gargantuan almost 2 years

    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?