Find index of an NSArray by passing value

2020-07-07 06:19发布

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).

5条回答
何必那么认真
2楼-- · 2020-07-07 06:56

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.

查看更多
够拽才男人
3楼-- · 2020-07-07 06:59

Use NSPredicate to filter an NSArray based on NSDictionary

array = [dictionary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(key == %@)", value]];

if([array count]>0)
{
value exists;
}
查看更多
\"骚年 ilove
4楼-- · 2020-07-07 07:11

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 
查看更多
▲ chillily
5楼-- · 2020-07-07 07:13

Combine objectAtIndex and indexOfObject like this:

[tmpArray objectAtIndex:[tmpArray indexOfObject:yourObject]];
查看更多
Animai°情兽
6楼-- · 2020-07-07 07:16

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.

查看更多
登录 后发表回答