我正在使用 Restkit 0.20 在核心数据中映射和存储对象。对于基本映射,它运行良好,但不适用于嵌套动态映射。这是我的示例响应:
[
{
"actor": {
"id": 7,
"first_name": "Murat",
"last_name": "Akbal"
},
"target": {
"content_type": "dress",
"type": {
"id": 1,
"name": "leggings",
"kind": "bottom"
},
"style": {
"id": 1,
"name": "sport"
},
"full_name": "Murat - sport leggings",
"id": 19,
}
},
{
"actor": {
"id": 7,
"first_name": "Murat",
"last_name": "Akbal"
},
"target": {
"content_type": "wardrobe",
"style": {
"id": 1,
"name": "sport"
},
"id": 38,
"season": "spring",
"name": "asdasd"
}
}
]
我使用以下实体映射来映射响应:
//create entity mapping
RKEntityMapping *objectMapping = [RKEntityMapping mappingForEntityForName:@"Action"
inManagedObjectStore:[RKObjectManager sharedManager].managedObjectStore];
//create dynamic mapping
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
//dressMapping and wardrobeMapping predefined mappings, they work well when mapping the wardobe and dress alone.
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if ([[representation valueForKey:@"content_type"] isEqualToString:@"wardrobe"]) {
return wardrobeMapping;
} else if ([[representation valueForKey:@"content_type"] isEqualToString:@"dress"]) {
return dressMapping;
}
return nil;
}];
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"target" toKeyPath:@"target" withMapping:dynamicMapping]];
//maps actor
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"actor" toKeyPath:@"actor" withMapping:actorMapping]];
最后,我将 objectMapping 注册为响应描述符:
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:objectMapping
pathPattern:nil
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
这不适用于我的示例响应,会出现以下错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Wardrobe 0x110e1a90> valueForUndefinedKey:]: the entity Wardrobe is not key value coding-compliant for the key "type".'
它询问衣柜中不存在的“类型”键,但存在于连衣裙中。不知何故,它试图用服装映射来映射衣柜。你对这个问题有什么想法吗?
仅供参考,coredata 中的目标类型是可转换的。