您的位置:首页 > 移动开发 > IOS开发

iOS --- 两个NSIndexPath对象的正确比较方式

2017-03-11 14:27 309 查看
在UITableView和UICollectionView中, 经常会遇到比较两个NSIndexPath对象是否相同的情况.


错误写法

if (currentIndexPath != lastIndexPath) {
// TODO
} else {
// TODO
}
1
2
3
4
5
1
2
3
4
5

因两个NSIndexPath对象分别指向不同的内存区域, 所以一般情况下, 以上的比较方式会永远成立.


分别使用section和row/item

只能分别对NSIndexPath对象的section与row或item进行判断: 

对于UITableView:
if (currentIndexPath.section != lastIndexPath.section ||
currentIndexPath.row != lastIndexPath.row) {
// TODO
} else {
// TODO
}
1
2
3
4
5
6
1
2
3
4
5
6

而对于UICollectionView:
if (currentIndexPath.section != lastIndexPath.section ||
currentIndexPath.item != lastIndexPath.item) {
// TODO
} else {
// TODO
}
1
2
3
4
5
6
1
2
3
4
5
6


使用NSObject的isEqual:方法

使用section和row/item的方式比较麻烦. 

其实NSIndexPath对象可以通过NSObject的isEqual:方法来进行比较, 实际上比较的是二者的hash值. 

因此跟二者的内存地址无关.
if (![currentIndexPath isEqual:lastIndexPath]) {
// TODO
}
1
2
3
1
2
3

至于hash值, 涉及到NSObject的更深层次的内容, 暂时还不是很清楚, 只是做了些简单的测试.
(lldb) po currentIndexPath
<NSIndexPath: 0x16ee8890> {length = 2, path = 0 - 0}

(lldb) po lastIndexPath
<NSIndexPath: 0x16d74470> {length = 2, path = 0 - 0}

(lldb) p currentIndexPath==lastIndexPath
(bool) $3 = false
(lldb) p currentIndexPath!=lastIndexPath
(bool) $4 = true
(lldb) p [currentIndexPath isEqual:lastIndexPath]
(BOOL) $5 = YES
(lldb) p [currentIndexPath compare:lastIndexPath]
(NSComparisonResult) $6 = 0
(lldb) p currentIndexPath.hash
(NSUInteger) $7 = 22
(lldb) p lastIndexPath.hash
(NSUInteger) $8 = 22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

两个NSIndexPath对象的hash值相等, 因此isEqual:的结果为YES. 

同样, 对应NSString, NSArray, NSDictionary等对象, 除了各自的isEqualToString, isEqualToArray, isEqualToDictionary之外, 

还可以使用isEqual:进行比较, 同样比较的是其hash值.


使用NSIndexPath的compare:方法

另外, 还可以使用NSIndexPath的compare:方法,
if ([currentIndexPath compare:lastIndexPath] != NSOrderedSame) {
// TODO
}
1
2
3
1
2
3

使用compare:比较的结果有三种: NSOrderedAscending, NSOrderedSame和NSOrderedDescending.


Demo

Demo地址:DemoNSObjectRelatedAll
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: