2012-05-04 47 views
0

我有幾個NSManagedObject類。我從服務器上拉下一些JSON數據,然後解析成一個NSDictionary對象。當從JSON轉換爲NSDictionary時,我的所有數據都被轉換爲NSStrings。當我然後映射這本字典我managedObject我得到這個:做setValuesForKeysWithDictionary時管理對象屬性的動態類型轉換

Unacceptable type of value for attribute: property = "idexpert"; desired type = NSNumber; given type = __NSCFString; value = 1.' 

所以我managedobject正在尋找一個NSNumber,但它得到一個字符串,並拋出一個異常

有沒有一種方式,當我打電話setValuesForKeysWithDictionary我可以自動地爲他們將要進入​​的管理對象正確地轉換值。

謝謝!

回答

0

如果你正在接收的json實際上有數字值並且它們被轉換爲字符串,你應該得到一個新的json解析器。我推薦NXJson。否則,不會有任何魔法鑄造發生。

如果json返回諸如{「idexpert」:「1」}這樣的字符串,那麼你可以重載setValuesForKeysWithDictionary並執行下面的代碼;


-(void)setValuesForKeysWithDictionary:(NSDictionary *)d{ 
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:d]; 
    NSString *value = [newDict valueForKey:@"idexpert"]; 
    [newDict setValue:[NSNumber numberWithLong:[value longValue]] forKey:@"idexpert"]; 
    [super setValuesForKeysWithDictionary:newDict]; 
} 
1

管理JSON的最好方法屬性,同時節省核心數據是寫一個通用的功能,可以覆蓋setValuesForKeysWithDictionary按如下:

@implementation NSManagedObject (safeSetValuesKeysWithDictionary) 

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues dateFormatter:(NSDateFormatter *)dateFormatter 
{ 
    NSDictionary *attributes = [[self entity] attributesByName]; 
    for (NSString *attribute in attributes) { 
     id value = [keyedValues objectForKey:attribute]; 
     if (value == nil) { 
      continue; 
     } 
     NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType]; 
     if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) { 
      value = [value stringValue]; 
     } else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) { 
      value = [NSNumber numberWithInteger:[value integerValue]]; 
     } else if ((attributeType == NSFloatAttributeType) && ([value isKindOfClass:[NSString class]])) { 
      value = [NSNumber numberWithDouble:[value doubleValue]]; 
     } else if ((attributeType == NSDateAttributeType) && ([value isKindOfClass:[NSString class]]) && (dateFormatter != nil)) { 
      value = [dateFormatter dateFromString:value]; 
     } 
     [self setValue:value forKey:attribute]; 
    } 
} 
@end 

欲瞭解更多詳情,請參閱此鏈接在這裏:http://www.cimgf.com/2011/06/02/saving-json-to-core-data/