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).
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.
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
anObjectAn object.Return Value
The lowest index whose corresponding array value is equal to
anObject. If none of the objects in the array is equal toanObject, returnsNSNotFound.Discussion
Objects are considered equal if
isEqual:returnsYES.Important: If
anObjectisnilan exception is raised.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With