Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa -- toggling a BOOL without repeating its name

If a BOOL has a nice short name, it's easy enough to write:

myBOOL = !myBOOL;

But what if the BOOL has a long name?

objectWithLongishName.memberWithLongishName.submember.myBOOL = !(objectWithLongishName.memberWithLongishName.submember.myBOOL);  

. . . does not look so pretty.

I'm wondering if there is an easy way to toggle the BOOL without entering its name twice?

like image 476
William Jockusch Avatar asked Jul 22 '10 20:07

William Jockusch


1 Answers

Here's another:

MyBooleanYaddaYadda ^= YES;

This is kinda brittle - it will break on legacy C code that implies that any nonzero integer evaluates to true. But then again, so will Apple framework code - I encountered cases in Cocoa where a nonzero, non-one int, when passed as a BOOL, would not cause the same effect as passing a YES.

However, it does not rely on the bit pattern of YES - only on NO being 0. Which is pretty much a given, considering the way C interprets integers as logical values. Also, it does not assume the actual datatype of BOOL (which on Cocoa is signed char, by the way).

The bit pattern of YES on Cocoa is 1. But that's not a universal convention. On some platforms with no built-in boolean datatype, the integer constant that serves as a logical TRUE is -1 - all one bits. That's 0xFFFFFFFF if interpreted as unsigned. This coding has a vague advantage that bitwize NOT (the ~ operator in C ) is equivalent to logical NOT (the ! operator in C). That is, ~0xFFFFFFFF is 0, i. e. ~TRUE is FALSE. Doesn't work that way if TRUE is defined as 1.

like image 133
Seva Alekseyev Avatar answered Oct 23 '22 01:10

Seva Alekseyev