Search code examples
objective-cuitableviewios6

How do you correctly get a row value from a table view?


I have implemented code that returns 0 every time. I'm trying to remove a string from a mutable array with the row value selected after hitting a button.

Related code:

- (IBAction)remove:(id)sender {
    NSIndexPath *selectedIndexPath = [_tableView2 indexPathForSelectedRow];
    [names removeObject:[NSString stringWithFormat:@"%i",selectedIndexPath.row]];
    testLabel.text=[NSString stringWithFormat:@"%i",selectedIndexPath.row];
    [_tableView2 reloadData];
}

The test label shows 0 every time the button is pressed, no matter where the tableview is selected.

Let me know if there is other relevant code (like the tableView) that you want me to post.


Solution

  • For a UITableView, the selected row concept is only valid while the user is touching the row. For that reason indexPathForSelectedRow is documented as returning “An index path identifying the row and section indexes of the selected row or nil if the index path is invalid.”

    My opinion is that you are obtaining a nil result, and later calling the row method in that nil results in the zero that your are seeing as your name.

    The solution depends on the rest of your data source implementation, but probably will involve storing the tapped index in didSelectRowAtIndexPath: to later use it in your remove method.

    (I supposed that you are not using the allowsMultipleSelectionDuringEditing option nor are you editing the table).