18

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?

4

4 回答 4

51

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

于 2009-11-28T17:58:27.613 回答
13

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.

于 2009-11-28T19:09:22.010 回答
4

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

于 2011-12-31T15:53:16.277 回答
1

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

于 2014-01-08T12:30:56.303 回答