Skip to content

Latest commit

 

History

History
150 lines (117 loc) · 5.97 KB

2013-04-08-bool.md

File metadata and controls

150 lines (117 loc) · 5.97 KB
title author category tags excerpt status
BOOL / bool / Boolean / NSCFBoolean
Mattt Thompson
Objective-C
nshipster, popular
Once again, encoding our logical universe into the cold, calculating bytecode of computers forces us to deal with these questions one way or another. And as you'll see from our discussion of boolean types in Objective-C and its kin, truth is indeed stranger than fiction.
swift
n/a

We've talked before about the philosophical and technical concerns of nothingness in programming. This week, our attention turns to another fundamental matter: Truth.

Truth. Vēritās. The entire charter of Philosophy is founded upon the pursuit of it, and yet its exact meaning and implications still elude us. Does truth exist independently, or is it defined contingently against falsity? Can a proposition be at once both true and false? Is there absolute truth in anything, or is everything relative?

Once again, encoding our logical universe into the cold, calculating bytecode of computers forces us to deal with these questions one way or another. And as you'll see from our discussion of boolean types in Objective-C and its kin, truth is indeed stranger than fiction.


Objective-C defines BOOL to encode truth value. It is a typedef of a signed char, with the macros YES and NO to represent true and false, respectively.

Boolean values are used in conditionals, such as if or while statements, to conditionally perform logic or repeat execution. When evaluating a conditional statement, the value 0 is considered "false", while any other value is considered "true". Because NULL and nil are defined as 0, conditional statements on these nonexistent values are also evaluated as "false".

In Objective-C, use the BOOL type for parameters, properties, and instance variables dealing with truth values. When assigning literal values, use the YES and NO macros.

The Wrong Answer to the Wrong Question

Novice programmers often include an equality operator when evaluating conditionals:

if ([a isEqual:b] == YES) {
  ...
}

Not only is this unnecessary, but depending on the left-hand value, it may also cause unexpected results, as described in the Big Nerd Ranch blog post, "BOOL's Sharp Edges":

static BOOL different (int a, int b) {
    return a - b;
}

An overly clever C programmer might take some satisfaction in the simplicity of this approach: indeed, two integers are equal if and only if their difference is 0.

However, because of the reality of BOOL being typedef'd as a signed char, this will not behave as expected:

if (different(11, 10) == YES) {
  printf ("11 != 10\n");
} else {
  printf ("11 == 10\n");
}

if (different(10, 11) == YES) {
  printf ("10 != 11\n");
} else {
  printf ("10 == 11\n");
}

if (different(512, 256) == YES) {
  printf ("512 != 256\n");
} else {
  printf ("512 == 256\n");
}

This evaluates to:

11 != 10
10 == 11
512 == 256

Now, this might be acceptable for JavaScript, but Objective-C don't suffer fools gladly.

Deriving truth value directly from an arithmetic operation is never a good idea. Like the sentence "Colorless green ideas sleep furiously", it may be grammatical (after all, BOOL is a signed char like any other, so it could be treated as a number), but it doesn't make sense semantically. Instead, use the result of the == operator, or cast values into booleans with the ! (or !!) operator.

The Truth About NSNumber and BOOL

Pop quiz: what is the output of the following expression?

NSLog(@"%@", [@(YES) class]);

The answer:

__NSCFBoolean

Wait, what?

All this time, we've been led to believe that NSNumber boxes primitives into an object representation. Any other integer- or float-derived NSNumber object shows its class to be __NSCFNumber. What gives?

NSCFBoolean is a private class in the NSNumber class cluster. It is a bridge to the CFBooleanRef type, which is used to wrap boolean values for Core Foundation property lists and collections. CFBoolean defines the constants kCFBooleanTrue and kCFBooleanFalse. Because CFNumberRef and CFBooleanRef are different types in Core Foundation, it makes sense that they are represented by different bridging classes in NSNumber.

For most people, boolean values and boxed objects "just work", and don't really care what goes into making the sausage. But here at NSHipster, we're all about sausages.


So, to recap, here is a table of all of the truth types and values in Objective-C:

Name Typedef Header True Value False Value
BOOL signed char objc.h YES NO
bool _Bool (int) stdbool.h true false
Boolean unsigned char MacTypes.h TRUE FALSE
NSNumber __NSCFBoolean Foundation.h @(YES) @(NO)
CFBooleanRef struct CoreFoundation.h kCFBooleanTrue kCFBooleanFalse