Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a boolean value to a NSDictionary?

People also ask

How do you give a Boolean a value?

To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.

How do you add value in Nsmutabledictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).

How do I set up Boolean?

' The ' bool ' type can store only two values: true or false . To create a variable of type bool, do the same thing you did with int or string . First write the type name, ' bool ,' then the variable name and then, probably, the initial value of the variable.

How do you set a Boolean value in Objective C?

To set a BOOL, you need to wrap the number in a value object with [NSNumber numberWithBool:NO] . But there's little reason to do that. Key-Value Coding is a roundabout way to accomplish this. Either do self.


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


As jcampbell1 pointed out, now you can use literal syntax for NSNumbers:

NSDictionary *data = @{
                      // when you always pass same value
                      @"someKey" : @YES
                      // if you want to pass some boolean variable
                      @"anotherKey" : @(someVariable)
                      };