接收int类型的集合元素不是iOS中的客观c对象

时间:2013-12-07 19:05:06

标签: ios nsdictionary

我有以下字典:

NSDictionary* jsonDict = @{
                               @"firstName": txtFirstName.text,
                               @"lastName": txtLastName.text,
                               @"email": txtEmailAddress.text,
                               @"password": txtPassword.text,
                               @"imageUrl": imageUrl,
                               @"facebookId": [fbId integerValue],
                              };

在最后一个元素中,我需要使用一个整数,但是我收到错误:

collection element of type int is not an objective c object

如何在此元素中使用int值?

6 个答案:

答案 0 :(得分:54)

应该是:

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

NSDictionary仅适用于对象,因此,我们无法仅存储intintegerbool s或任何其他原语< / em>数据类型。

[fbId integerValue]返回一个原始整数值(,它不是一个对象
因此,我们需要封装 primitive 数据类型并将它们转换为对象。这就是为什么我们需要使用类似NSNumber的类来使对象简单地存储这个废话。

更多阅读:http://rypress.com/tutorials/objective-c/data-types/nsnumber.html

答案 1 :(得分:6)

OR,假设fbID是NSString

@"facebookId": @([fbId intValue]);

就像Java中的自动装箱一样。 @将任何原始数字转换为NSNumber对象。

答案 2 :(得分:5)

假设 fbID int那么应该是这样的:

@"facebookId": @(fbId)

答案 3 :(得分:1)

NSDictionary只能保存对象(例如NSString,NSNumber,NSArray等),而不是原始值(例如int,float,double等)。几乎所有Objective-C中的封装都是如此。要存储号码,请使用NSNumber:

NSDictionary *dictionary = @{@"key" : [NSNumber numberWithInt:integerValue]]};

答案 4 :(得分:0)

您必须在Dictionary中使用@(%value%)作为非指针数据类型值存储。

@"facebookId": @(fbId)

答案 5 :(得分:-1)

我最终使用NSNumber

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber * myNumber = [f numberFromString:fbId];
    [f release];