问题
I'm looking for a way to test if to index paths are equal, and by equal I mean equal on every level? I tried compare:
but it seems not to work, I always get true when compared with NSOrderedSame
even if the indexes are definitely not the same.
回答1:
Almost all Objective-C objects can be compared using the isEqual:
method. So, to test equality, you just need [itemCategoryIndexPath isEqual:indexPath]
, and you're good to go. Now, this works because NSObject
implements isEqual:
, so all objects automatically have that method, but if a certain class doesn't override it, isEqual:
will just compare object pointers.
In the case of NSIndexPath
, since the isEqual:
method has been overridden, you can compare the objects as you were to expect. But if I were to write a new class, MyObject
and not override the method, [instanceOfMyObject isEqual:anotherInstanceOfMyObject]
would effectively be the same as instanceOfMyObject == anotherInstanceOfMyObject
.
You can read more in the NSObject Protocol Reference.
回答2:
In Swift you use ==
to compare if NSIndexPaths are the same.
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 uses ==
for value comparisons. ===
is used for detecting when two variables reference the exact same instance (location in memory etc). Interestingly, the indexPath1 === indexPath2
shows that NSIndexPath is built to share the same instance whenever the values (section row) match, so even if you were comparing instances, it would still be valid.
This answer taken almost completely from this fantastic SO answer from drewag and reproduced here since this is the first Google result for 'compare indexpath' and we are not supposed to just paste a link.
来源:https://stackoverflow.com/questions/6379101/how-to-compare-two-nsindexpaths