How do I get specific values from a NSIndexPath
Asked Answered
P

1

7

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

Panhandle answered 7/5, 2011 at 2:17 Comment(3)
Is this really your code? Are you using a custom table view subclass? I don't think there's a method called indexPathsForSelectedRows. You also can't just assign an NSIndexPath instance to an NSArray pointer.Kalinin
Apple has undocumented methods for multiselection in a UITableView(like the mail app) that is where indexPathsForSelectedRows comes fromPanhandle
As of iOS 5 this code is 100% app store safe! (not that I care, I'm hell post-SDK)Ulani
P
10

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, ....

Pehlevi answered 7/5, 2011 at 2:45 Comment(1)
You can also do path.row to get the value at the indexBacchic

© 2022 - 2024 — McMap. All rights reserved.