Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get specific values from a NSIndexPath

I have a NSArray with NSIndexPaths inside of it

NSArray *array = [self.tableView indexPathsForSelectedRows];

for (int i = 0; i < [array count]; i++) {
    NSLog(@"%@",[array objectAtIndex:i]);
}

The NSLog returns this:

<NSIndexPath 0x5772fc0> 2 indexes [0, 0]
<NSIndexPath 0x577cfa0> 2 indexes [0, 1]
<NSIndexPath 0x577dfa0> 2 indexes [0, 2]

I am trying to get the second value from the indexPath into just a plain NSInteger

like image 582
Heli0s Avatar asked May 07 '11 02:05

Heli0s


People also ask

What is the IndexPath item?

Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section.

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

You can use NSIndexPath's -indexAtPosition: method to get the last index:

NSIndexPath *path = ...; // Initialize the path.
NSUInteger lastIndex = [path indexAtPosition:[path length] - 1]; // Gets you the '2' in [0, 2]

In your case, you can use the following (as Josh mentioned in his comment, I'm assuming you're working with a custom subclass of UITableView, because it doesn't have that specific method (-indexPathsForSelectedRows:)):

NSArray *indexes = [self.tableView indexPathsForSelectedRows];
for (NSIndexPath *path in indexes) {
    NSUInteger index = [path indexAtPosition:[path length] - 1];
    NSLog(@"%lu", index);
}

That will print out 0, 1, 2, ....

like image 126
Itai Ferber Avatar answered Sep 30 '22 00:09

Itai Ferber