How can I add a boolean value to a NSDictionary? How can I add a boolean value to a NSDictionary? objective-c objective-c

How can I add a boolean value to a NSDictionary?


You use NSNumber.

It has init... and number... methods that take booleans, just as it does integers and so on.

From the NSNumber class reference:

// Creates and returns an NSNumber object containing a // given value, treating it as a BOOL.+ (NSNumber *)numberWithBool:(BOOL)value

and:

// Returns an NSNumber object initialized to contain a// given value, treated as a BOOL.- (id)initWithBool:(BOOL)value

and:

// Returns the receiver’s value as a BOOL.- (BOOL)boolValue


The new syntax since Apple LLVM Compiler 4.0

dictionary[@"key1"] = @(boolValue);dictionary[@"key2"] = @YES;

The syntax converts BOOL to NSNumber, which is acceptable to NSDictionary.


If you are declaring it as a literal and you are using clang v3.1 or above, you should use @NO / @YES if you are declaring it as a literal. E.g.

NSMutableDictionary* foo = [@{ @"key": @NO } mutableCopy];foo[@"bar"] = @YES;

For more info on that:

http://clang.llvm.org/docs/ObjectiveCLiterals.html