Reputation: 29767
I have the following dictionary:
NSDictionary* jsonDict = @{
@"firstName": txtFirstName.text,
@"lastName": txtLastName.text,
@"email": txtEmailAddress.text,
@"password": txtPassword.text,
@"imageUrl": imageUrl,
@"facebookId": [fbId integerValue],
};
In the last element, I need to use an integer, but I am receiving the error:
collection element of type int is not an objective c object
How can I use an int value in this element?
Upvotes: 20
Views: 26482
Reputation: 3727
You have to use @(%value%) for non pointer datatype value store in Dictionary.
@"facebookId": @(fbId)
Upvotes: 2
Reputation: 7712
assuming fbID is an int
then It should be like:
@"facebookId": @(fbId)
Upvotes: 8
Reputation: 29767
I ended up using an NSNumber
:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:fbId];
[f release];
Upvotes: -1
Reputation: 20244
should be:
@"facebookId": [NSNumber numberWithInt:[fbId intValue]];
NSDictionary
works with objects only and as a result, we can't store simply int
s or integer
s or bool
s or anyother primitive datatypes.
[fbId integerValue]
returns a primitive integer value (which is not an object)
Hence we need to encapsulate primitive datatypes and make them into objects. which is why we need to use a class like NSNumber
to make an object to simply store this crap.
more reading: http://rypress.com/tutorials/objective-c/data-types/nsnumber.html
Upvotes: 69
Reputation: 1673
NSDictionary can only hold objects (e.g. NSString, NSNumber, NSArray, etc.), not primitive values (e.g. int, float, double, etc.). The same goes for almost all encapsulation in Objective-C. To store numbers, use NSNumber:
NSDictionary *dictionary = @{@"key" : [NSNumber numberWithInt:integerValue]]};
Upvotes: 1
Reputation: 15589
OR, assuming fbID is an NSString
,
@"facebookId": @([fbId intValue]);
its like autoboxing in Java. @ converts any primitive number to NSNumber object.
Upvotes: 6