I often need to set table view cells to an initial selected state for which I use the following code:
[self.tableView selectRowAtIndexPath:indexPath
animated:NO scrollPosition:UITableViewScrollPositionNone];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:YES];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
I am using selectRowAtIndexPath:indexPath and setSelected:YES at the same time, because I do not fully understand which of both ways are the preferred way to select a cell programmatically.
Which one of the statements should I use and why?
I believe the method you want to use is
selectRowAtIndexPath:animated:scrollPosition:. Usually, you should leave management of cell state to the table view. In case of selection, it stores and maintains a set of selected index paths, so the proper row will remain selected after a different cell is reused for it. There’s also no need to call both methods, it is simply redundant.