0

Following a previous SO question, I was trying to get my tableView cell selection right, with saving and other stuff.

I've making it toggle, but can't save the indexPath and retrieve it to display the selection even when the user leaves the view or restarts the app.

Here's the code:

@property (nonatomic, strong) NSIndexPath* lastIndexPath;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...
    if([self.lastIndexPath isEqual:indexPath])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    ...
}


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

    if(self.lastIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                                        cellForRowAtIndexPath:self.lastIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
    }
    if([self.lastIndexPath isEqual:indexPath])
    {
        self.lastIndexPath = nil;
    }
    else
    {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.lastIndexPath = indexPath;
    }


    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSNumber numberWithInt:self.lastIndexPath.row] forKey:@"selectedCell"];
    [defaults synchronize];

}

How can I save the indexPath and retrieve it to display the selection even after the user closes and reopens the view?

Thanks in advance.

Community
  • 1
  • 1
Phillip
  • 4,276
  • 7
  • 42
  • 74

2 Answers2

1

You should add this in viewWillAppear.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *lastRow = [defaults objectForKey:@"selectedCell"];
if (lastRow) {
    self.lastIndexPath = [NSIndexPath indexPathForRow:lastRow.integerValue inSection:0];
}

When you restart the app, you should get the lastIndexPath from NSUserDefaults, otherwise it is nil.

gabbler
  • 13,626
  • 4
  • 32
  • 44
0

You should do two things:

1) In didSelectRowAtIndexPath, reload the previously selected row if it is visible 2) In cellForRowAtIndexPath, do a check in there if indexpath.row is the same as your selected cell. If it is, give it the check mark, if not then don't

Choppin Broccoli
  • 3,048
  • 2
  • 21
  • 28
  • There is no need to reload the table view when a row is selected. Just reload the previously selected row if it is visible. – rmaddy Dec 09 '14 at 22:23