didSelectRowAtIndexPath returns wrong IndexPath

2019-03-17 10:20发布

问题:

I have encountered a really puzzling bug. The first row of my UITableView returns 1 and the second one returns 0 in the indexPath! How is that even possible?

In my `-(void)viewDidLoad` everything is still fine. I am highlighting the first row successfully with

currentRow = 0;
[tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0] 
  animated:NO scrollPosition:UITableViewScrollPositionNone];

I have the variable currentRow for tracking which row is selected (another control changes according to which one is currently selected).

Now in my `didDeselectRowAtIndexPath` delegate function I have:

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
...
NSLog(@"IndexPath: %@", [indexPath description]);
}

The log shows the following:

IndexPath: <NSIndexPath 0x79509d0> 2 indexes [0, 0] when I touch the second row, and IndexPath: <NSIndexPath 0x79509d0> 2 indexes [0, 1] when I touch the first row.

There are is no row insertion or deletion or sorting, etc., not even scrolling. It is a simple UITableView, grouped style, with 1 section and 3 rows. What could be causing this?

Thanks for your help,
S

回答1:

You have implemented didDeselectRowAtIndexPath. It will be fired when the row is no longer selected.

When you touch the second row, the first row is no longer selected, so [0, 1] will be shown.
When you touch the first row again, the second row is now no longer selected, so [0, 0] will be shown.

These are totally expected.

Implement didSelectRowAtIndexPath if you need it to respond when the row is selected.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //                                       ^
    ...

    NSLog(@"IndexPath: %@", [indexPath description]);
}


回答2:

Despite the title, the overloaded method is in fact didDeselectRowAtIndexPath, so it sounds like the behaviour is correct -- when the 1th row is touched, the 0th becomes deselected, and vice versa.