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
.