How can I add a boolean value to a NSDictionary?

Objective CIphoneCocoa TouchUikit

Objective C Problem Overview


Well, for integers I would use NSNumber. But YES and NO aren't objects, I guess. A.f.a.i.k. I can only add objects to an NSDictionary, right?

I couldn't find any wrapper class for booleans. Is there any?

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

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.

Solution 3 - Objective C

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

Solution 4 - Objective C

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)
                      };

Solution 5 - Objective C

Try this:

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:[NSNumber numberWithBool:TRUE]  forKey:@"Pratik"];
[dic setObject:[NSNumber numberWithBool:FALSE] forKey:@"Sachin"];

if ([dic[@"Pratik"] boolValue])
{
    NSLog(@"Boolean is TRUE for 'Pratik'");
}
else
{
    NSLog(@"Boolean is FALSE for 'Pratik'");
}

if ([dic[@"Sachin"] boolValue])
{
    NSLog(@"Boolean is TRUE for 'Sachin'");
}
else
{
    NSLog(@"Boolean is FALSE for 'Sachin'");
}

The output will be as following:

Boolean is TRUE for 'Pratik'

Boolean is FALSE for 'Sachin'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThanksView Question on Stackoverflow
Solution 1 - Objective CharmsView Answer on Stackoverflow
Solution 2 - Objective CBrianView Answer on Stackoverflow
Solution 3 - Objective CsabalabaView Answer on Stackoverflow
Solution 4 - Objective CVojtaView Answer on Stackoverflow
Solution 5 - Objective CNSPratikView Answer on Stackoverflow