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 m开发者_如何学JAVAine.
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?
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.
Given that this code is toggling between UITableViewCellAccessoryCheckmark
and UITableViewCellAccessoryNone
and is attempting to be concise, another alternative -- which I find clearer -- would be:
cell.accessoryType ^= UITableViewCellAccessoryCheckmark|UITableViewCellAccessoryNone;
This statement is more clear in its intent and obviates the need for a conditional statement -- which might or might not be useful depending on how frequently it is called.
精彩评论