ios - Objective C - NSArray的indexOfObject : not work

标签 ios objective-c nsarray

我使用[items indexOfObject:items.lastObject]来获取最后一个索引,但此代码返回nil。为什么会出现这种情况?

enter image description here

最佳答案

数组中的第一个和最后一个对象都是使用“固定空间”系统项创建的条形按钮项。

调用indexOfObject:的结果是0,而不是nil。这意味着在索引 0 处找到该对象。 indexOfObject: 无法返回 nil。如果未找到对象,它将返回特殊值 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: 的实现将返回 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/

相关文章:

ios - 从iphone图片库中获取所有图片并显示在UICollectionView中

ios - Swift 将导航栏标题更改为所选表格 View 单元格的标题

ios - 无法将字符串转换为仅限 iOS 13.3 的 NSDate

iphone - 释放 Root View Controller

ios - UICollectionView 单元格未在 reloadData 上清除

objective-c - NSErrorDomain + NS_ERROR_ENUM 使类型查找不明确。为什么?

ios - 在 .h 文件中声明 NSString - Objective c

iphone - Cocoa 数组到字符串被截断

nsarray - Swift 中的元组数组

objective-c - 最佳实践? - 数组/字典作为核心数据实体属性