Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

ios - indexPathForSelectedRow returning nil

I have a UITableViewController with a segue where I'm trying to get the currently selected row:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([[segue identifier] isEqualToString:@"EditFilterElementSegue"]){
        // Get the element that was clicked and pass it to the view controller for display
        NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
        Element *element = [fetchedResultsController objectAtIndexPath:selectedIndexPath];
        FilterElementTableViewController *vc = segue.destinationViewController;
        vc.filter = filter;
        vc.element = element;
    }
}

The problem is indexPathForSelectedRow is returning nil. The docs say nil is returned "if the index path is invalid". If I add:

        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:0];
        selectedIndexPath = [self.tableView indexPathForSelectedRow];

selectedIndexPath is valid. So, I'm currently assuming the row is somehow getting unselected. Can anyone tell me how to figure out if this is the case and what might be causing it?

This code worked fine until I converted to using NSFetchedResultsController (which otherwise is working). I also use indexPathForSelectedRow in several other table view controllers where it works fine (one of which also uses NSFetchedResultsController).

I've also tried breaking in didSelectRowAtIndexPath, but the same thing happens there. (expected since it's called after prepareForSegue.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A possible cause is that you've written something in one of the UITableViewDelegate methods -

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

It's a common practice to deselect the row which has just been selected.

Update:

In Swift 4.2, xcode 10:

Just comment the line

tableView.deselectRow(at: indexPath, animated: true)

in the function

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...