UITableViewCellAccessory Multiple sections

I am trying to add a checkmark to a UITableViewCell when a user selects it. I have the following code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if (selectedCell.accessoryType == UITableViewCellAccessoryNone) {
        selectedCell.accessoryType = UITableViewCellAccessoryCheckmark;

The table has multiple sections and the problem is that if I select a row the checkmark is duplicated in other rows in different sections. The checkmark also moves between rows in each section as you scroll up and down the page. I have managed to loop through the table and document how many rows have the accessory checkmark and each time it is the number it should be, it doesn't count the other rows that get added without me meaning to.

Any help would be greatly appreciated.


The cell you set as selected is being reused by the UITableView as you scroll up and down the view.

The proper approach is to track selection in a model object or check in tableView:cellForRowAtIndexPath: to see if indexPath is in the table view's indexPathsForSelectedRows and only show the checkmark in that case. Because cellForRowAtIndexPath: is called for both reused and newly created cells, you shouldn't encounter this issue in either scenario.

This assumes you have set tableView.allowsMultipleSelection to YES.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = // do some initing here

    // determine if this cell is currently selected
    if ([tableView.indexPathsForSelectedRows containsObject:indexPath]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;

Need Your Help

Enabling vi key bindings in IPython qtconsole

ipython readline qtconsole

I have enabled vi mode in my ~/.inputrc using the following lines in my mac.

Why is my Sieve of Eratosthenes giving some composite numbers?

c++ primes sieve-of-eratosthenes

So, after running my implementation of the Sieve of Eratosthenes, for some cases, it also gives me composite numbers.