1

我正在尝试将 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也是)和孩子/父母的关系/连接?(“内容”中包含的文件夹没有“内容”属性)

4

1 回答 1

1

看一下动态映射的 RestKit 文档:动态对象映射

根据文档,您应该在创建动态映射后添加此行objectMapping

[folderMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"contents" toKeyPath:@"children" withMapping:objectMapping]];

您将"contents"属性指定为使用动态映射进行映射。此外,您不必担心内部文件夹没有"contents"字段。如果"contents"不存在,RestKit 应该优雅地忽略它,并且您的NSSet *children属性将自动设置nil为该对象。

于 2013-05-20T15:07:05.510 回答