(更完整的代码见我的要点:https ://gist.github.com/AlistairIsrael/6521763 )
我正在尝试从本地 JSON 文件映射“具有多”关系:
[
{
"name": "fruits",
"items": [
{
"name": "apple",
},
{
"name": "banana",
}
]
}
]
我有基于 wiki 上的示例代码的代码: https ://github.com/RestKit/RestKit/wiki/Object-Mapping#performing-a-mapping
客户端.m
NSString* path = [[NSBundle mainBundle] pathForResource: @"collections" ofType: @"json"];
NSError* e;
NSString* json = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&e];
id data = [RKNSJSONSerialization objectFromData:[json dataUsingEncoding:NSUTF8StringEncoding] error:&e];
NSMutableArray* collections = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (id record in data) {
Collection* collection = [Collection new];
RKMappingOperation* op = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:collections mapping:[Collection mapping]];
[op start];
[collections addObject:collection];
}
return [NSArray arrayWithArray:collections];
当我只想映射一个“平面”对象数组时,这很好用。然而,当我试图映射一个嵌套对象数组时,我遇到了困难——这些对象本身具有一个属性,该属性是其他对象的集合。
收藏.m
@interface Collection : NSObject
@property (nonatomic, copy) NSString* name;
@property (nonatomic, copy) NSArray* items;
@implementation Collection
+ (RKMapping*) mapping {
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Collection class]];
[mapping addAttributeMappingsFromArray:@[@"name"]];
RKPropertyMapping* itemsMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"items" toKeyPath:@"items" withMapping:[Item mapping]]
// Commenting out the following line works, but no items
[mapping addPropertyMapping:itemsMapping];
return mapping;
}
如果我在 中注释掉第 13 行Collection mapping:
,那么中的代码Client.m
会给我一个数组Collection
(没有items
)。
但事实上,当我尝试RKRelationshipMapping
为 a 的 items 属性添加时Collection
,我不断得到:
没有数据源就无法执行关系映射
我也尝试过使用RKMapperOperation
与此要点中的代码类似的代码:
https ://gist.github.com/kmc239/5846568
无济于事——我得到一个空的NSArray
.
我错过了什么?