Tag Archive | "NO"

Objective-C and the Properties of BOOL

At a basic level, boolean logic allows for a value to be either true or false, on or off, 1 or 0. The ways in which boolean types are implemented vary widely across languages and implementations. At the most granular level, computers work with bits that are either set to on or off, whereas some boolean data types in databases cater for three or even four values: 1, 0, null or undefined. Dennis Ritchie’s original C language lacked a boolean type at all but it was added in C99, and C’s primitive ‘bool’ type is available in Objective-C. ‘bool’ can be set to either true or false, 1 or 0.

Objective-C has implemented a more standard boolean property – it offers the BOOL type in addition to the primitive ‘bool’. The Cocoa and Cocoa Touch API’s use BOOL as the standard message response in favour of ‘bool’, so it is a property you must get to understand, and should code your own methods using BOOL as well.

Unlike most other things in Objective-C, BOOL is NOT an object, it is a raw data type. The standard values of BOOL are YES and NO rather than true or false, or 1 or 0. However, under the bonnet YES and NO are simply definitions given to the preprocessor as aliases for 1 and 0. In Cocoa Touch YES and NO are defined in NSObjCRuntime.h:-

#if !defined(YES)
    #define YES (BOOL)1

#if !defined(NO)
    #define NO (BOOL)0

This means that BOOL values are NEVER ‘YES’ and ‘NO’ so you cannot test them as such:-

if (myBOOL == 'YES') { ... }

…and they are NOT objects, so you cannot send the message:-

if ([myBOOL isEqualToString: @"YES"]) { ... }

Instead you must test them for true or false, or zero or non-zero:-

if (myBOOL) { ... }


if (!myBOOL) { ... }

If you want to log the value of a BOOL property using NSLog, then you can use the decimal signed integer format identifier %d:-

NSLog(@"MyBOOL value is %d", myBOOL);

Because BOOL represents 1 and 0 internally, you can also use the ternary operator to test BOOL values:-

myBOOL ? NSLog(@"Yes") : NSLog(@"No");

…and you can use this technique to convert between bool and BOOL should you so wish:-

mybool = myBOOL ? true : false;

Remembering that BOOL is NOT an object type makes it easy to remember how to declare BOOL properties, namely:-


…rather than using a pointer:-


BOOL properties can be set with any of YES / NO, true / false or 1 / 0. All map back to 1 or 0.

Understanding that Objective-C’s BOOL data type is simply mapped to 1 and 0 makes working with BOOL values completely straightforward!

Posted in Development, iPhone Development, Objective-CComments (2)


For more information about our services…

Contact Us

Wordle of the Day

Image from software at http://wordle.net
Data by Web Trends Now