我尝试将JSON响应映射到NSManagedObject
的实例,但我不了解如何正确设置关系/连接。
我的课程是:
@interface CloudObject : NSManagedObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) CloudFolder *parent;
@end
@interface CloudFolder : CloudObject
@property (nonatomic, retain) NSSet *children;
@end
@interface CloudFile : CloudObject
@property (nonatomic, retain) NSString * mimeType;
@end
JSON是这样的:
{
"name": "Folder1",
"is_dir": true,
"contents": [
{ "name": "Folder2", "is_dir": true }
{ "name": "File1", "is_dir": false, "mime_type": "audio/mpeg" }
]
}
我使用RKDynamicMapping
来映射响应(根对象):
RKEntityMapping *fileMapping = [RKEntityMapping mappingForEntityForName:@"CloudFile" inManagedObjectStore:managedObjectStore];
[fileMapping addAttributeMappingsFromDictionary:@{@"name": @"name", @"mime_type": @"mimeType"}];
RKEntityMapping *folderMapping = [RKEntityMapping mappingForEntityForName:@"CloudFolder" inManagedObjectStore:managedObjectStore];
[folderMapping addAttributeMappingsFromDictionary:@{@"name": @"name"}];
RKDynamicMapping *objectMapping = [[RKDynamicMapping alloc] init];
[objectMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"is_dir" expectedValue:[NSNumber numberWithBool:NO] objectMapping:fileMapping]];
[objectMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"is_dir" expectedValue:[NSNumber numberWithBool:YES] objectMapping:folderMapping]];
但是我现在如何设置与@"contents"
(也应该是RKDynamicMapping
)和孩子/父母的关系/连接? (包含在'内容中的文件夹'没有'内容' -attribute)
答案 0 :(得分:1)
查看有关动态映射的RestKit文档:Dynamic Object Mapping。
根据文档,在创建动态映射objectMapping
后,您似乎应该添加此行:
[folderMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"contents" toKeyPath:@"children" withMapping:objectMapping]];
您将"contents"
属性指定为与动态映射映射。此外,您不必担心内部文件夹没有"contents"
字段。如果"contents"
不存在,RestKit应该优雅地忽略它,并且NSSet *children
属性将自动设置为该对象的nil
。