1

我有一个从 Web 服务接收的 JSON 中提取的数组。当我使用 NSLOG 查看数组的内容时,它显示如下:

{ ?    Category = "New Products";
    CategoryID = 104;
    SubCategories =     (
    );
}

我需要获取 Category 和 CategoryID 值并将它们分配给托管对象“newProductCategory”。分配与字符串类型相对应的类别值没有问题,并且将硬编码数字分配给应该接收类别 ID 的 int 32 类型也没有问题。但是在将 CategoryID 值转换为将被接受为 int 32 类型的任何内容时,我一直在苦苦挣扎。

将该值转换为这行代码可消化的东西而不是零的正确语法是什么?

[newProductCategory setValue : 0 forKey : @"productCategoryID"];

这是我失败的尝试之一,可能会提供有用的信息。当我尝试...

        // Pull category record "i" from JSON        
        NSArray * categoryProperties = [categories objectAtIndex:i];
        NSNumber * productCategoryID = [categoryProperties valueForKey:@"CategoryID"];

...然后我尝试以上述格式分配它,使用 productCategoryID 代替零,它会产生以下错误:

'NSInvalidArgumentException',原因:'不可接受的属性值类型:property = "parentCategoryID"; 所需类型 = NSNumber; 给定类型 = __NSCFString; 值 = 104。

4

2 回答 2

3

即使你在 CoreData 中指定了 int32,你也会传递一个 NSNumber 对象,并且似乎你从 json 解析中得到了一个 NSString(你可以试试 NSStringFromClass([productCategoryID class]) 的日志来确定)。你可以试试 :

NSString * productCategoryID = [categoryProperties valueForKey:@"CategoryID"];
newProductCategory.productCategoryID = @([productCategoryID intValue]);
//or
newProductCategory.productCategoryID = [NSNumber numberWithInt:[productCategoryID intValue]];
于 2013-02-14T15:45:58.893 回答
0

你需要设置NSNumber,有2种方式:

[newProductCategory setValue:@(0) forKey:@"productCategoryID"];

或者

[newProductCategory setValue:[NSNumber numberWithInt:0] forKey:@"productCategoryID"];
于 2013-02-13T19:53:17.063 回答