Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing NSIndexPath

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?

like image 851
Jason Avatar asked Jun 24 '13 15:06

Jason


People also ask

How does swift compare to IndexPath?

=== is used for detecting when two variables reference the exact same instance. Interestingly, the indexPath1 === indexPath2 shows that NSIndexPath is built to share the same instance whenever the values match, so even if you were comparing instances, it would still be valid.

What is NSIndexPath?

An object containing a list of indexes that bridges to IndexPath ; use NSIndexPath when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.4+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

What is NSIndexPath in Swift?

NSIndexPath has a read-only structure that contains two Int property sections and rows if you're working with UITableViews or a section and item if you're working with UICollectionViews . You create them with the NSIndexPath:forRow:inSection: factory method: Swift. 1. let indexPath = NSIndexPath(forRow: 1, inSection: 0 ...

What is IndexPath Objective C?

Index path is generally a set of two values representing row and section of a table view. Index path can be created in objective C as well as Swift as both are native language of iOS Development.


1 Answers

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.

like image 60
Doc Avatar answered Oct 12 '22 01:10

Doc