iOS-兩個(gè)NSIndexPath對(duì)象的正確比較方式

在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í)還不是很清楚, 只是做了些簡(jiǎn)單的測(cè)試.

(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 概述在iOS開發(fā)中UITableView可以說是使用最廣泛的控件,我們平時(shí)使用的軟件中到處都可以看到它的影子,類似...
    liudhkk閱讀 9,307評(píng)論 3 38
  • { 24、Sqlite數(shù)據(jù)庫 1、存儲(chǔ)大數(shù)據(jù)量,增刪改查,常見管理系統(tǒng):Oracle、MSSQLServer、DB...
    CYC666閱讀 1,060評(píng)論 0 1
  • 前言 對(duì)數(shù)據(jù)的等同性判斷包括對(duì)基本數(shù)據(jù)類型等同性的判斷和對(duì)象等同性的判斷。對(duì)基本數(shù)據(jù)類型等同性的判斷是非常簡(jiǎn)單的,...
    VV木公子閱讀 1,791評(píng)論 0 8
  • 2017/12/5「能量世界1189天」 豆丁公寓 深夜,和老莊、汪小涵、康康、波波、曉靜在莊嬸廚房收金。心里對(duì)能...
    陳艷霞小樹媽閱讀 397評(píng)論 0 0

友情鏈接更多精彩內(nèi)容