The BOOL
type is used for boolean values in Objective-C. It has two values, YES
, and NO
, in contrast to the more common "true" and "false".
Its behavior is straightforward and identical to the C language's.
BOOL areEqual = (1 == 1); // areEqual is YES
BOOL areNotEqual = !areEqual // areNotEqual is NO
NSCAssert(areEqual, "Mathematics is a lie"); // Assertion passes
BOOL shouldFlatterReader = YES;
if (shouldFlatterReader) {
NSLog(@"Only the very smartest programmers read this kind of material.");
}
A BOOL
is a primitive, and so it cannot be stored directly in a Foundation collection. It must be wrapped in an NSNumber
. Clang provides special syntax for this:
NSNumber * yes = @YES; // Equivalent to [NSNumber numberWithBool:YES]
NSNumber * no = @NO; // Equivalent to [NSNumber numberWithBool:NO]
The BOOL
implementation is directly based on C's, in that it is a typedef of the C99 standard type bool
. The YES
and NO
values are defined to __objc_yes
and __objc_no
, respectively. These special values are compiler builtins introduced by Clang, which are translated to (BOOL)1
and (BOOL)0
. If they are not available, YES
and NO
are defined directly as the cast-integer form. The definitions are found in the Objective-C runtime header objc.h