Comparing NSIndexPath

Jason picture Jason · Jun 24, 2013 · Viewed 11.4k times · Source

This is going to be something really stupid, but I have this code in my cellForRowAtIndexPath:

if ([self.indexPathSelected compare:indexPath] == NSOrderedSame)
{
    NSLog(@" %d %d %d %d", self.indexPathSelected.row, self.indexPathSelected.section, indexPath.row, indexPath.section);
}

This prints:

0 0 0 0

0 0 1 0

0 0 2 0

0 0 3 0

0 0 4 0

0 0 5 0

I was expecting it to only print 0 0 0 0.

What am I doing wrong here?

Answer

Doc picture Doc · Jun 24, 2013

Since you're setting indexPathSelected to nil, you want to make sure it's non-nil before doing a compare.

if (self.indexPathSelected && [self.indexPathSelected compare:indexPath] == NSOrderedSame)
{
    NSLog(@" %d %d %d %d", self.indexPathSelected.row, self.indexPathSelected.section, indexPath.row, indexPath.section);
}

According to the documentation on NSIndexPath's compare method:

Parameters

indexPath

Index path to compare.

This value must not be nil. If the value is nil, the behavior is undefined.