1

I am aware that on row selection you can have a check mark appear by using the following code:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;

How do I get the check mark to stay on the selected rows if the user is too move between different view controllers?

Thanks

Larme
  • 24,190
  • 6
  • 51
  • 81

1 Answers1

0

In your UITableViewController set clearsSelectionOnViewWillAppear to NO.

If you want the selection preserved after the table view controller has been deallocated you'll need to store the selected items somewhere like NSUserDefaults.

-(void)viewDidLoad
{    
    [super viewDidLoad]; 
    NSArray *previousSelection = [[NSUserDefaults standardDefaults] objectForKey:@"selection"];
    for (NSArray *selection in previousSelection) {
         [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selection[1] inSection:selection[0]] animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSArray *selections = [self.tableView indexPathsForSelectedRows];
    NSMutableArray *selectionsToSave = [NSMutableArray array];
    for (NSIndexPath *selection in selections) {
        [selectionsToSave addObject:@[selection.section, selection.row]];
    }
    [[NSUserDefaults standardDefaults] setObject:selectionsToSave forKey:@"selection"];
    // Save as iOS 7 now saves less frequently - see note
    [[NSUserDefaults standardDefaults] synchronize];
}

Note on the use of synchronize

EDIT: Corrected answer thanks to @rmaddy pointing out that you can only put simple types in NSUserDefaults.

Community
  • 1
  • 1
Rich
  • 8,108
  • 5
  • 46
  • 59
  • This won't work. You can't store `NSIndexPath` objects in `NSUserDefaults`. – rmaddy Apr 13 '14 at 16:44
  • @rmaddy that should be better! Thanks for spotting that :) – Rich Apr 13 '14 at 16:53
  • That should work but personally I would never do this. It would be better to store some sort of key for each selected row in case the order or number of rows ever change. – rmaddy Apr 13 '14 at 16:55
  • Yeah, you'd be better off using core data to back the data, but the OP hasn't given much info...! – Rich Apr 13 '14 at 16:56