Reputation: 10116
Why does the following result in a BAD_ACCESS error?
NSDictionary *header=[[NSDictionary alloc]initWithObjectsAndKeys:@"fred",@"title",1,@"count", nil];
Can you have different types of objects as values in NSDictionary, including another NSDictionary?
Upvotes: 7
Views: 7710
Reputation: 19071
You can put any type of object into an NSDictionary
. So while @"fred"
is OK, 1
is not, as an integer is not an object. If you want to put a number in a dictionary, wrap it in an NSNumber
:
NSDictionary *header = { @"title": @"fred", @"count": @1 };
Upvotes: 15
Reputation: 5960
The only requirement is that is be an object. It's up to you to handle the objects properly in your code, but presumably, you can keep track of their types based on the keys.
1 is not an object. If you want t o put a number into a dictionary you may want to convert it to an NSNumber.
Upvotes: 0
Reputation: 400274
An NSDictionary
can only contain Objective-C objects in it (such as NSString
and NSArray
), it cannot contain primitive types like int
, float
, or char*
. Given those constraints, heterogeneous dictionaries are perfectly legal.
If you want to include a number such as 1
as a key or value, you should wrap it with an NSNumber
:
NSDictionary *header=[[NSDictionary alloc] initWithObjectsAndKeys:
@"fred", @"title",
[NSNumber numberWithInt:1], @"count",
nil];
Upvotes: 0
Reputation: 4239
Not the way you have it. The number 1 is a primitive and the NSArray object can hold only objects. Create a NSNumber for the "1" and then it will store it.
Upvotes: 0