Reputation: 10172
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).
Upvotes: 7
Views: 7814
Reputation: 6383
Combine objectAtIndex
and indexOfObject
like this:
[tmpArray objectAtIndex:[tmpArray indexOfObject:yourObject]];
Upvotes: 0
Reputation: 1751
Use NSPredicate
to filter an NSArray
based on NSDictionary
array = [dictionary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(key == %@)", value]];
if([array count]>0)
{
value exists;
}
Upvotes: 0
Reputation: 14113
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
Upvotes: 4
Reputation: 53000
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.
Upvotes: 9
Reputation: 48398
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 toanObject
, returnsNSNotFound
.Discussion
Objects are considered equal if
isEqual:
returnsYES
.Important: If
anObject
isnil
an exception is raised.
Upvotes: 6