Objective c 执行setValuesForKeysWithDictionary时托管对象属性的动态类型转换

Objective c 执行setValuesForKeysWithDictionary时托管对象属性的动态类型转换,objective-c,cocoa-touch,Objective C,Cocoa Touch,我有几个NSManagedObject类。我正在从服务器中提取一些JSON数据,并将其解析为NSDictionary对象。当从JSON转换为NSDictionary时,我的所有数据都转换为NSString。然后,当我将此词典映射到我的managedObject时,我得到以下结果: Unacceptable type of value for attribute: property = "idexpert"; desired type = NSNumber; given type = __NSCF

我有几个NSManagedObject类。我正在从服务器中提取一些JSON数据,并将其解析为NSDictionary对象。当从JSON转换为NSDictionary时,我的所有数据都转换为NSString。然后,当我将此词典映射到我的managedObject时,我得到以下结果:

Unacceptable type of value for attribute: property = "idexpert"; desired type = NSNumber; given type = __NSCFString; value = 1.'
所以我的managedobject正在寻找一个NSNumber,但它得到一个字符串并抛出一个异常

有没有一种方法,当我调用
setValuesForKeysWithDictionary
时,我可以自动为他们要进入的managedobject正确地强制转换值


谢谢

如果您接收的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];
}

在保存核心数据时管理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
有关更多详细信息,请参阅此处的链接: