How to compare two NSIndexPaths?

Valentin Radu picture Valentin Radu · Jun 16, 2011 · Viewed 19.2k times · Source

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.

Answer

Itai Ferber picture Itai Ferber · Jun 17, 2011

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.