我使用[items indexOfObject:items.lastObject]
来获取最后一个索引,但此代码返回nil
。为什么会出现这种情况?
最佳答案
数组中的第一个和最后一个对象都是使用“固定空间”系统项创建的条形按钮项。
调用indexOfObject:
的结果是0
,而不是nil
。这意味着在索引 0
处找到该对象。 indexOfObject:
无法返回 nil
。如果未找到对象,它将返回特殊值 NSNotFound
,它是 -1
的无符号值。
来自 indexOfObject:
的文档:
Starting at index
0
, each element of the array is passed as an argument to anisEqual:
message sent to anObject until a match is found or the end of the array is reached. Objects are considered equal ifisEqual:
(declared in theNSObject
protocol) returnsYES
.
如果使用相同的系统项(可能还有一些其他属性)创建两个栏按钮项实例,则 UIBarButtonItem isEqual:
的实现将返回 YES
。
indexOfObject:
不是基于对象的实例,而是基于 isEqual:
。
如果您想根据对象的标识(其地址)而不是 isEqual:
查找对象的索引,请使用 indexOfObjectIdenticalTo:
。
p [items indexOfObjectIdenticalTo:items.lastObject]
将为您提供 6
而不是 0
。
关于ios - Objective C - NSArray的indexOfObject : not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034143/