在执行setValuesForKeysWithDictionary时对托管对象属性进行动态类型转换

时间:2012-05-04 19:47:30

标签: objective-c cocoa-touch

我有一些NSManagedObject类。我从服务器中提取一些JSON数据,我将其解析为NSDictionary对象。当从JSON转换为NSDictionary时,我的所有数据都被转换为NSStrings。当我将这个字典映射到我的托管对象时,我得到了这个:

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

所以我的managedobject正在寻找一个NSNumber,但它正在获取一个字符串并抛出异常

有没有办法在我调用setValuesForKeysWithDictionary时,我可以自动为他们要进入的托管对象强制转换值?

谢谢!

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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];
}