[英]How to compare two NSIndexPaths?
我正在尋找一種方法來測試索引路徑是否相等,並且相等意味着在每個級別上相等? 我嘗試compare:
但是似乎不起作用,即使索引絕對不相同,與NSOrderedSame
相比,我也總是正確的。
幾乎所有的Objective-C對象都可以使用isEqual:
方法進行比較。 因此,要測試相等性,您只需要[itemCategoryIndexPath isEqual:indexPath]
,就可以了。 現在,這是NSObject
,因為NSObject
實現了isEqual:
因此所有對象都自動具有該方法,但是如果某個類未覆蓋該方法,則isEqual:
只會比較對象指針。
對於NSIndexPath
,由於isEqual:
方法已被覆蓋,因此可以按預期比較對象。 但是,如果我要編寫一個新類MyObject
並且不重寫該方法,則[instanceOfMyObject isEqual:anotherInstanceOfMyObject]
實際上將與instanceOfMyObject == anotherInstanceOfMyObject
相同。
您可以在《 NSObject協議參考》中閱讀更多內容。
在Swift中,您使用==
比較NSIndexPaths是否相同。
import UIKit
var indexPath1 = NSIndexPath(forRow: 1, inSection: 0)
var indexPath2 = NSIndexPath(forRow: 1, inSection: 0)
var indexPath3 = NSIndexPath(forRow: 2, inSection: 0)
var indexPath4 = indexPath1
println(indexPath1 == indexPath2) // prints "true"
println(indexPath1 == indexPath3) // prints "false"
println(indexPath1 == indexPath4) // prints "true"
println(indexPath1 === indexPath2) // prints "true"
println(indexPath1 === indexPath3) // prints "false"
println(indexPath1 === indexPath4) // prints "true"
Swift使用==
進行值比較。 ===
用於檢測兩個變量何時引用完全相同的實例(在內存中的位置等)。 有趣的是, indexPath1 === indexPath2
表明,只要值(節行)匹配,NSIndexPath便構建為共享同一實例,因此即使您正在比較實例,它仍然有效。
此答案幾乎完全取自drewag的出色SO答案,並在此處復制,因為這是Google針對“比較索引路徑”的第一個結果,我們不應該僅粘貼鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.