【问题标题】:RestKit direct foregin key mappingRestKit 直接外键映射
【发布时间】:2012-11-27 13:33:26
【问题描述】:

我有以下 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",
         }...

【问题讨论】:

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


    【解决方案1】:

    似乎有问题的行是

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

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

    【讨论】:

    • 我的设置是正确的,我将userCreator中的对象映射到属性id,该属性设置为主要属性,userCreator中的对象只是一个字符串,表示id
    • 那么你必须完全放弃映射。然后你会得到字符串。
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    相关资源
    最近更新 更多