Friday, June 7, 2013

UITableView indexPathsForSelectedRows example in Objective C (iOS).


UITableView indexPathsForSelectedRows

Returns the index paths represented the selected rows.

- (NSArray *)indexPathsForSelectedRows

Return Value of [UITableView indexPathsForSelectedRows]
An array of index-path objects each identifying a row through its section and row index. Returns nil if there are no selected rows.

UITableView indexPathsForSelectedRows example.
Since NSIndexPath implements compare:, sorting the array is trivial:

NSArray *sortedIndexPaths = [[tableView indexPathsforSelectedRows]
    sortedArrayUsingSelector:@selector(compare:)];

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

UITableView indexPathsForSelectedRows example.
You'll want to access the row and section properties like so:

-(IBAction)goToView2{
    //get all section selectioned items into an array
    themesChosed=[tView indexPathsForSelectedRows];//tView is the outlet of my UITableView and themesChosed is an NSArray declared in the .h file
    for (int i=0; i<=[themesChosed count]; i++) {
        NSIndexPath *thisPath = [themesChosed objectAtIndex:i];
        NSLog(@"row = %i, section = %i", thisPath.row, thisPath.section);
    }
}

End of UITableView indexPathsForSelectedRows example article.