[iOS] collection element of type int is not an objective c object

滿有趣的,原來大家都會遇到,切到 swift 可能就沒有這個問題:

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

should be:

@"facebookId": [NSNumber numberWithInt:[fbId intValue]];

NSDictionary works with objects only and as a result, we can’t store simply ints or integers or bools 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

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *