接收int类型的collection元素不是iOS中的目标c对象



我有以下字典:

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值?

应为:

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

NSDictionary仅适用于对象,因此,我们不能简单地存储ints或integers或bools或任何其他基元数据类型。

[fbId integerValue]返回一个基元整数值(,它不是对象
因此,我们需要封装原语数据类型,并将它们制成对象。这就是为什么我们需要使用像NSNumber这样的类来创建一个对象来简单地存储这些垃圾。

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

假设fbIDint,那么它应该是:

@"facebookId": @(fbId)

OR,假设fbID是NSString

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

这就像Java中的自动装箱。@将任何基元编号转换为NSNumber对象。

对于Dictionary中的非指针数据类型值存储,必须使用@(%value%)。

@"facebookId": @(fbId)

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

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

我最终使用了NSNumber:

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

最新更新