iphoneaccessorytype

Please explain this weird way of setting cell accessory


I saw the following line of code here while Googling for an answer to another question of mine.

cell.accessoryType = (UITableViewCellAccessoryNone + UITableViewCellAccessoryCheckmark) - cell.accessoryType;

It seems, from that thread, that the code works. I'm just wondering, isn't that code redundant ? If you know the accessoryType, why subtract it from that expression?


Solution

  • If the accessoryType was UITableViewCellAccessoryNone, then the net of the expression would be setting it to UITableViewCellAccessoryCheckmark.

    If the accessoryType was UITableViewCellAccessoryCheckmark, then the net of the expression would be setting it to UITableViewCellAccessoryNone.

    It's just a shortcut to saying

    if (cell.accessoryType == UITableViewCellAccessoryNone)
        cell.accessoryType = UITableViewCellAccessoryCheckmark
    else if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
        cell.accessoryType = UITableViewCellAccessoryNone
    

    Definitely an example of obfuscated code... I'd avoid it.