Mikael Konutgan

BOOL

I recently bought the NSHipster book and was rereading BOOL / bool / Boolean / NSCFBoolean and noticed the part where Mattt explains how comparing with YES can be dangerous, because BOOL is a typedef of signed char. I remembered that on 64-bit devices BOOL is actually a typedef of bool, the native (as of C99) boolean type.

The intersting thing is that the native bool type is safe, safe in the sence that a variable typed as bool can only ever have the values 0 or 1. So

BOOL value = 5;
NSLog(@"%d", value);

prints 5 on all iPhone’s except for the iPhone 5s, where it prints 1.

Also e.g. (BOOL)5 is 1 on 64-bit devices, getting rid of the awkward !! pattern to safely cast other types into booleans.

Even so, you probably shouldn’t compare boolean expressions with YES, but at least you will get the expected result on 64-bit devices going forward, as functions or methods returning BOOL will always return 0 or 1.