Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two NSIndexPaths?

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.

like image 867
Rad'Val Avatar asked Jun 16 '11 21:06

Rad'Val


2 Answers

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.

like image 190
Itai Ferber Avatar answered Oct 21 '22 14:10

Itai Ferber


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.

like image 34
Joshua Dance Avatar answered Oct 21 '22 12:10

Joshua Dance