如何在RestKit 0.20中实现`hasOne:withMapping:`?

时间:2013-10-21 22:29:14

标签: cocoa core-data restkit restkit-0.20

我有一个JSON数据结构,用于排序

的项目
{
    "id": "8a1a39479d03d959", 
    "sortOrder": 3, 
    "timestamp": 1381669499.11, 
}

和另一个只有一个项目的文件结构:

{
    "id": "d88e3c3d1630db4c", 
    "item": "8a1a39479d03d959", 
    "timestamp": 1381669505.364, 
    "version": 2
}

我一直在努力让这种映射工作,以至于我在项目JSON中添加了一个[files]列表来映射关系。但是,阅读较旧的post on the Google group,我发现它曾经被认为可以像这样映射这些关系(没有经过测试的代码,只是解释上面的链接):

RKManagedObjectMapping *itemMapping = [RKManagedObjectMapping mappingForClass:[Item class]];
itemMapping.primaryKeyAttribute = @"itemID";
[itemMapping mapKeyPath:@"sortOrder" toAttribute:@"sortOrder"];
[itemMapping mapKeyPath:@"id" toAttribute:@"itemID"];

RKManagedObjectMapping *fileMapping = [RKManagedObjectMapping mappingForClass:[File class]];
fileMapping.primaryKeyAttribute = @"fileID";
[fileMapping mapKeyPath:@"id" toAttribute:@"fileID"];
[fileMapping mapKeyPath:@"item" toAttribute:@"itemID"];
[fileMapping mapKeyPath:@"version" toAttribute:@"version"];

[fileMapping hasOne:@"item" withMapping:itemMapping];
[fileMapping connectRelationship:@"organization" withObjectForPrimaryKeyAttribute:@"itemID"];

然而,RestKit 0.20中不再存在hasOne:withMapping:。现在正确的方法是将一对多关系映射为在JSON中作为简单字符串返回的id?仅供参考,我在这个项目中使用CoreData集成。

2 个答案:

答案 0 :(得分:1)

好的,您的映射将项目标识设置为identifier。在文件上,这对应于什么 - 它需要。添加一个瞬态属性并将item映射到它(让我们称之为itemIdentifier)。现在,您可以设置关系映射以填充核心数据关系(应该是双向的,我假设item<< - > files):

[fileMapping addConnectionForRelationship:@"item" connectedBy:@{ @"itemIdentifier": @"identifier" }];

答案 1 :(得分:0)

试试这个:

RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Item"
                                               inManagedObjectStore:[YourManagedObjectStore];
[mapping addAttributeMappingsFromDictionary:@{
                                              @"sortOrder": @"sortOrder",
                                              @"id":@"itemID"
                                              }];

mapping.identificationAttributes = @[@"itemID"];

[mapping addRelationshipMappingWithSourceKeyPath:@"organization"
                                         mapping:fileMapping];

我希望它有所帮助。