Objective C - NSArray 的 indexOfObject:无效
Objective C - NSArray's indexOfObject: not work
我用[items indexOfObject:items.lastObject]
获取最后一个索引,但是这段代码returns nil
。为什么会这样?
数组中的第一个和最后一个对象都是使用 "fixed space" 的系统项创建的条形按钮项。
调用indexOfObject:
的结果是0
,不是nil
。这意味着在索引 0
处找到了该对象。 indexOfObject:
不能 return nil
。如果未找到对象,它 return 是特殊值 NSNotFound
,它是 -1
的无符号值。
来自 indexOfObject:
的文档:
Starting at index 0
, each element of the array is passed as an argument to an isEqual:
message sent to anObject until a match is found or the end of the array is reached. Objects are considered equal if isEqual:
(declared in the NSObject
protocol) returns YES
.
如果两个栏按钮项目实例是使用相同的系统项目(可能还有一些其他属性)创建的,UIBarButtonItem isEqual:
的实现将 return YES
。
indexOfObject:
不是基于对象的实例,而是基于isEqual:
.
如果要根据对象的标识(其地址)而不是 isEqual:
查找对象的索引,请使用 indexOfObjectIdenticalTo:
.
p [items indexOfObjectIdenticalTo:items.lastObject]
会给你 6
而不是 0
.
我用[items indexOfObject:items.lastObject]
获取最后一个索引,但是这段代码returns nil
。为什么会这样?
数组中的第一个和最后一个对象都是使用 "fixed space" 的系统项创建的条形按钮项。
调用indexOfObject:
的结果是0
,不是nil
。这意味着在索引 0
处找到了该对象。 indexOfObject:
不能 return nil
。如果未找到对象,它 return 是特殊值 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:
的实现将 return YES
。
indexOfObject:
不是基于对象的实例,而是基于isEqual:
.
如果要根据对象的标识(其地址)而不是 isEqual:
查找对象的索引,请使用 indexOfObjectIdenticalTo:
.
p [items indexOfObjectIdenticalTo:items.lastObject]
会给你 6
而不是 0
.