Can NSDictionary contain different types of objects as values?

Why does the following result occur with the BAD_ACCESS error?

NSDictionary *header=[[NSDictionary alloc]initWithObjectsAndKeys:@"fred",@"title",1,@"count", nil]; 

Do you have different types of objects as values ​​in an NSDictionary, including another NSDictionary?

+7
source share
4 answers

You can put any type of object in an NSDictionary . Therefore, while @"fred" is ok, 1 not, since the integer is not an object. If you want to put a number in a dictionary, wrap it in NSNumber :

 NSDictionary *header = { @"title": @"fred", @"count": @1 }; 
+15
source

Not like yours. The number 1 is primitive, and an NSArray can only contain objects. Create an NSNumber for "1" and then save it.

0
source

An NSDictionary can only contain Objective-C objects in it (for example, NSString and NSArray ), it cannot contain primitive types such as int , float or char* . Given these limitations, heterogeneous dictionaries are perfectly legal.

If you want to include a number, such as 1 , as a key or value, you must wrap it with NSNumber :

 NSDictionary *header=[[NSDictionary alloc] initWithObjectsAndKeys: @"fred", @"title", [NSNumber numberWithInt:1], @"count", nil]; 
0
source

The only requirement is to be an object. It is up to you to properly process the objects in your code, but apparently you can track their types based on keys.

1 is not an object. If you want you to enter a number in the dictionary, you can convert it to NSNumber.

0
source

All Articles