How to compare two NSIndexPaths?

强颜欢笑 提交于 2019-12-03 23:29:12

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.

Joshua Dance

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!