Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of an NSArray by passing value

Is it possible in an NSArray to find out if a given value exists or not in the array (without searching it using a for loop)? Any default random method. I went through the documentation, but didn't find much relevant.

Please also tell me about valueForKey method (I was unable to get that from doc).

like image 843
rptwsthi Avatar asked May 26 '11 05:05

rptwsthi


3 Answers

The containsObject: method will usually give you what you're asking - while its name sounds like you are querying for a specific instance (i.e. two object with the same semantic value would not match) it actually invokes isEqual: on the objects so it is testing by value.

If you want the index of the item, as your title suggests, use indexOfObject:, it also invokes isEqual: to locate the match.

valueForKey: is for when you have an array of dictionaries; it looks up the key in each dictionary and returns and array of the results.

like image 65
CRD Avatar answered Nov 07 '22 16:11

CRD


I believe you want to use the indexOfObject method. From the documentation:

indexOfObject:

Returns the lowest index whose corresponding array value is equal to a given object.

- (NSUInteger)indexOfObject:(id)anObject

Parameters

anObject

An object.

Return Value

The lowest index whose corresponding array value is equal to anObject. If none of the objects in the array is equal to anObject, returns NSNotFound.

Discussion

Objects are considered equal if isEqual: returns YES.

Important: If anObject is nil an exception is raised.

like image 37
PengOne Avatar answered Nov 07 '22 17:11

PengOne


You can use :

NSInteger idx = [myArray indexOfObject:obj]; 

to find index of object.
And to check if object is there or not in array you may use :

- (BOOL)containsObject:(id)anObject 
like image 20
Nitish Avatar answered Nov 07 '22 17:11

Nitish