3

在这里,我使用NSManagedObject.

第一个问题是,当我尝试将空值分配给属性时,它给出了错误:

desired type = NSString;

给定类型 =null。

NSDictionary从 JSON 文件序列化中获取值。但是当值为空时,我得到了崩溃,给出了上述错误:

desired type = NSString;

给定类型 =null。

为此,我正在编写以下代码,但仍然出现错误。我应该怎么做才能正确处理空值。

    NSManagedObject *updateDevice=[results lastObject];

           if([results count] > 0){
                        //if(1){
              NSLog(@"updateeeee");
                        //continue;
   [updateDevice setValue:[NSString stringWithFormat:@"%@",[dict objectForKey:@"clip_image_path"]] forKey:@"clip_image_path"];
   [updateDevice setValue:[dict objectForKey:@"clip_name"] forKey:@"clip_name"];
   [updateDevice setValue:[dict objectForKey:@"page_categorisation"] forKey:@"page_categorisation"];

以下属性具有空值

  [updateDevice setValue:[dict objectForKey:@"personality_company_master_values"] == [NSNull null] ? nil:dict    forKey:@"personality_company_master_values"];

  [updateDevice setValue:[dict objectForKey:@"category_master_values"] == [NSNull null] ? nil: dict forKey:@"category_master_values"];

  [updateDevice setValue:[dict objectForKey:@"brand_master_values"] == [NSNull null] ? nil:dict forKey:@"brand_master_values"];

  [updateDevice setValue:[dict objectForKey:@"company_master_values"] == [NSNull null] ? nil:dict forKey:@"company_master_values"];

  [updateDevice setValue:[dict objectForKey:@"product_master_values"] == [NSNull null] ? nil:dict forKey:@"product_master_values"];

  [updateDevice setValue:[dict objectForKey:@"industry_master_values"] == [NSNull null] ? nil:dict forKey:@"industry_master_values"];
4

3 回答 3

1

You are getting the error cited in your question title because this line:

[updateDevice setValue:[dict objectForKey:@"personality_company_master_values"] == [NSNull null] ? nil:dict    forKey:@"personality_company_master_values"];

is passing dict to the setValue: if the condition fails. Try replacing with:

[updateDevice setValue:[dict objectForKey:@"personality_company_master_values"] == [NSNull null] ? nil: [dict objectForKey:@"personality_company_master_values"] forKey:@"personality_company_master_values"];

ie. pass the relevant element of the dictionary, not the dictionary itself.

于 2016-07-04T23:10:19.283 回答
0

您的代码中有一些错误。首先,最好使用isEqual:方法而不是==比较NSNull

[[dict objectForKey:@"personality_company_master_values"] isEqual:[NSNull null]]

另一个问题是您如何使用?:运算符。如果设置括号,它将如下所示:

[updateDevice setValue:([dict objectForKey:@"personality_company_master_values"] == [NSNull null] ? nil:dict) forKey:@"personality_company_master_values"];

你确定dict不是nil吗?或者也许你错过了]

于 2016-07-04T11:03:53.507 回答
0

请在设置值之前使用此代码

 if ([updateDevice valueForKey:@"personality_company_master_values"] && ![[updateDevice valueForKey:@"personality_company_master_values"] isKindOfClass:[NSNull class]])
 [updateDevice setValue:[dict objectForKey:@"personality_company_master_values"]    forKey:@"personality_company_master_values"];
于 2016-07-04T11:07:59.117 回答