Objective-C dictionary inserting a BOOL
OK, I'm a little confused. It's probably just a triviality.
I've got a function which looks something like this:
- (void)getNumbersForNews:(BOOL)news andMails:(BOOL)mails {
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:news forKey:@"getNews"];
[parameters setValue:mails forKey:@"getMails"];...}
It doesn't matter whether I use setValue:forKey:
or setObject:ForKey:
, I'm always getting a warning:
"Passing argument 1 of set... makes pointer from integer without a cast"...
How on earth do I insert a bool into a dictionary?
Values in an NSDictionary
must be objects. To solve this problem, wrap the booleans in NSNumber
objects:
[parameters setValue:[NSNumber numberWithBool:news] forKey:@"news"];
[parameters setValue:[NSNumber numberWithBool:mails] forKey:@"mails"];
Objective-C containers can store only Objective-C objects so you need to wrap you BOOL in some object. You can create a NSNumber object with [NSNumber numberWithBool]
and store the result.
Later you can get your boolean value back using NSNumber's -boolValue
.
Modern code for reference:
parameters[@"getNews"] = @(news);
A BOOL is not an object - it's a synonym for an int and has 0 or 1 as its values. As a result, it's not going to be put in an object-containing structure.
You can use NSNumber to create an object wrapper for any of the integer types; there's a constructor [NSNumber numberWithBool:]
that you can invoke to get an object, and then use that. Similarly, you can use that to get the object back again: [obj boolValue]
.