gpt4 book ai didi

ios - 当 RKEntityMapping 包含在同一个 JSON 中时如何添加连接

转载 作者:行者123 更新时间:2023-11-29 13:13:10 24 4
gpt4 key购买 nike

我正在尝试将 JSON 响应映射到 NSManagedObject 的实例,但我不明白如何正确设置关系/连接。

我的类(class)是:

@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)和 child / parent 的关系/连接? (“内容”中包含的文件夹没有“内容”属性)

最佳答案

查看动态映射的 RestKit 文档:Dynamic Object Mapping .

根据文档,看起来您应该在创建动态映射 objectMapping 之后添加这一行:

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

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

关于ios - 当 RKEntityMapping 包含在同一个 JSON 中时如何添加连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16650748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com