在UITableView和UICollectionView中, 经常会遇到比较两个NSIndexPath对象是否相同的情况.
错误写法
if (currentIndexPath != lastIndexPath) {
    // TODO
} else {
    // TODO
} 
因两个NSIndexPath对象分别指向不同的内存区域, 所以一般情况下, 以上的比较方式会永远成立.
分别使用section和row/item
只能分别对NSIndexPath对象的section与row或item进行判断: 
 对于UITableView:
if (currentIndexPath.section != lastIndexPath.section ||
    currentIndexPath.row != lastIndexPath.row) {
    // TODO
} else {
    // TODO
} 
而对于UICollectionView:
if (currentIndexPath.section != lastIndexPath.section ||
    currentIndexPath.item != lastIndexPath.item) {
    // TODO
} else {
    // TODO
} 
使用NSObject的isEqual:方法
使用section和row/item的方式比较麻烦. 
 其实NSIndexPath对象可以通过NSObject的isEqual:方法来进行比较, 实际上比较的是二者的hash值. 
 因此跟二者的内存地址无关.
if (![currentIndexPath isEqual:lastIndexPath]) {
    // TODO
} 
至于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 
两个NSIndexPath对象的hash值相等, 因此isEqual:的结果为YES. 
 同样, 对应NSString, NSArray, NSDictionary等对象, 除了各自的isEqualToString, isEqualToArray, isEqualToDictionary之外, 
 还可以使用isEqual:进行比较, 同样比较的是其hash值.
使用NSIndexPath的compare:方法
另外, 还可以使用NSIndexPath的compare:方法,
if ([currentIndexPath compare:lastIndexPath] != NSOrderedSame) {
    // TODO
} 
使用compare:比较的结果有三种: NSOrderedAscending, NSOrderedSame和NSOrderedDescending.
Demo
Demo地址:DemoNSObjectRelatedAll
iOS:正确比较NSIndexPath对象的方法
        
                  
                  
                  
                  
                            
在UITableView和UICollectionView中比较NSIndexPath对象时,错误的直接比较会导致始终返回不同。正确做法包括:分别比较section和row/item,使用NSIndexPath的isEqual:方法或compare:方法。isEqual:方法基于hash值比较,而compare:方法返回排序关系。通过这些方法,可以有效判断NSIndexPath对象的等价性。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					927
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            