通过传递值查找NSArray的索引

7

在NSArray中,是否有可能找出一个给定的值是否存在于数组中(不使用for循环搜索)?任何默认的随机方法。我查看了文档,但没有发现太多相关信息。

请您也介绍一下valueForKey方法(我从文档中无法理解它的含义)。

5个回答

9
containsObject:方法通常会给你想要的结果 - 虽然它的名称听起来像是在查询特定的实例(即两个具有相同语义值的对象不匹配),但实际上它会调用对象的isEqual:方法,因此它是按值测试的。
如果您想要项目的索引,如标题所示,请使用indexOfObject:,它也会调用isEqual:以定位匹配项。 valueForKey:用于当您有一个字典数组时;它在每个字典中查找键并返回结果数组。

6
我相信您想使用 indexOfObject 方法。从文档中可以得知:

indexOfObject:

返回与给定对象相等的最低索引对应的数组值。

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


感谢您的快速准确回复和编辑(+1),但CRD也描述了我所问的valueForKey。 - rptwsthi

4
您可以使用:

NSInteger idx = [myArray indexOfObject:obj]; 

查找对象的索引。
要检查对象是否存在于数组中,可以使用以下方法:

- (BOOL)containsObject:(id)anObject 

0
使用NSPredicate根据NSDictionary过滤NSArray
array = [dictionary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(key == %@)", value]];

if([array count]>0)
{
value exists;
}

0
objectAtIndexindexOfObject结合起来使用,就像这样:
[tmpArray objectAtIndex:[tmpArray indexOfObject:yourObject]];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接