在UITableView和UICollectionView中, 經(jīng)常會(huì)遇到比較兩個(gè)NSIndexPath對(duì)象是否相同的情況.
錯(cuò)誤寫法
if (currentIndexPath != lastIndexPath) {
// TODO
} else {
// TODO
}
因兩個(gè)NSIndexPath對(duì)象分別指向不同的內(nèi)存區(qū)域, 所以一般情況下, 以上的比較方式會(huì)永遠(yuǎn)成立.
分別使用section和row/item
只能分別對(duì)NSIndexPath對(duì)象的section與row或item進(jìn)行判斷:
對(duì)于UITableView:
if (currentIndexPath.section != lastIndexPath.section ||
currentIndexPath.row != lastIndexPath.row) {
// TODO
} else {
// TODO
}
而對(duì)于UICollectionView:
if (currentIndexPath.section != lastIndexPath.section ||
currentIndexPath.item != lastIndexPath.item) {
// TODO
} else {
// TODO
}
使用NSObject的isEqual:方法
使用section和row/item的方式比較麻煩.
其實(shí)NSIndexPath對(duì)象可以通過NSObject的isEqual:方法來進(jìn)行比較, 實(shí)際上比較的是二者的hash值.
因此跟二者的內(nèi)存地址無關(guān).
if (![currentIndexPath isEqual:lastIndexPath]) {
// TODO
}
至于hash值, 涉及到NSObject的更深層次的內(nèi)容, 暫時(shí)還不是很清楚, 只是做了些簡單的測試.
(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
兩個(gè)NSIndexPath對(duì)象的hash值相等, 因此isEqual:的結(jié)果為YES.
同樣, 對(duì)應(yīng)NSString, NSArray, NSDictionary等對(duì)象, 除了各自的isEqualToString, isEqualToArray, isEqualToDictionary之外,
還可以使用isEqual:進(jìn)行比較, 同樣比較的是其hash值.
使用NSIndexPath的compare:方法
另外, 還可以使用NSIndexPath的compare:方法,
if ([currentIndexPath compare:lastIndexPath] != NSOrderedSame) {
// TODO
}
使用compare:比較的結(jié)果有三種: NSOrderedAscending, NSOrderedSame和NSOrderedDescending.
Demo
Demo地址:DemoNSObjectRelatedAll