RestKit直接外键映射

时间:2012-11-27 13:33:26

标签: objective-c cocoa core-data foreign-keys restkit

我有以下JSON

{
   ...
   "users": [
            {
                "name": "Username 1"
                "id": "uid1",
            },
            {
                "name": "Username 2",
                "id": "uid2",                
                "userCreator": "uid1"
            },
            {
                "name": "Username 3",
                "id": "uid3",
                "userCreator": "uid1"
            }
        ]
}

在CoreData中,在User类(名为id,name的属性)中,我有一对多关系,名为userCreator,类为User

现在我需要映射JSON关系,我试过

RKManagedObjectMapping * mapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:[RKManagedObjectStore defaultObjectStore]];

mapping.primaryKeyAttribute = @"id";
[mapping mapAttributes:@"id", @"name", nil];

RKManagedObjectMapping * userCreatorMapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:[RKManagedObjectStore defaultObjectStore]];
userCreatorMapping.primaryKeyAttribute = @"id";
[userCreatorMapping mapAttributes:@"id", nil];

//[mapping hasOne:@"userCreator" withMapping:userCreatorMapping];
[mapping mapRelationship:@"userCreator" withMapping:userCreatorMapping];
[mapping connectRelationship:@"userCreator" withObjectForPrimaryKeyAttribute:@"id"];

哪种方法无效,正在制作

...
"users":[{
             "id":"uid1",
             "name":"Username 1"
         },
         {
             "id":"uid2",
             "name":"Username 2",
             "userCreator":{"id":"uid1"} // wanted "userCreator":"uid1",
         }...

1 个答案:

答案 0 :(得分:0)

似乎有违规行

userCreatorMapping.primaryKeyAttribute = @"id";
// ...
[mapping connectRelationship:@"userCreator" 
     withObjectForPrimaryKeyAttribute:@"id"];

虽然我不使用RK,但很明显你没有告诉userCreatorMapping要映射什么。你只是在双方都给它"id"