RestKit实体映射和父实体映射

时间:2012-05-17 15:15:44

标签: objective-c cocoa-touch core-data restkit

我有一个Person类(firstName和lastName的属性)和另一个实体Worker(工资和标题的属性)。在我的Core Data模型中,Person实体被设置为Worker实体的父实体。在我的AppDelegate中,我设置了我的映射...

RKManagedObjectMapping* personMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Person" inManagedObjectStore:objectManager.objectStore];
[personMapping mapKeyPath:@"firstName" toAttribute:@"firstName"];
[personMapping mapKeyPath:@"lastName" toAttribute:@"lastName"];    
[objectManager.mappingProvider addObjectMapping:personMapping];

RKManagedObjectMapping* workerMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Worker" inManagedObjectStore:objectManager.objectStore];
[workerMapping mapKeyPath:@"wage" toAttribute:@"wage"];
[workerMapping mapKeyPath:@"title" toAttribute:@"title"];
[objectManager.mappingProvider setMapping:workerMapping forKeyPath:@"workers"];    

RKManagedObjectSeeder* seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager];
[seeder seedObjectsFromFiles:@"people.json", nil];

...在people.json ......

{
    "workers":
    [
        {
            "firstName":"Rob",
            "lastName":"Johnson"
        },
        {
            "firstName":"John",
            "lastName":"Roberts"
        }
    ]
}

...现在,当我运行时,没有任何对象被播种。如何表达Worker类与Person具有相同映射的事实?我可以将它们添加到该映射但是感觉不对。

使用...

注册Person映射时也是如此
[objectManager.mappingProvider addObjectMapping:personMapping];

...我不使用RKManagedObjectMapping方法setMapping:forKeyPath:因为我们永远不会在这个应用程序中遇到一个Person,所以我们永远不会映射它。但我仍然希望它注册。对于个人的子实体。

1 个答案:

答案 0 :(得分:0)

您没有告诉对象映射器对firstNamelastName字段执行任何操作。您只定义了wagetitle的映射。为了使您的种子工作,您需要为JSON的结构以及您的Web服务定义映射,并添加如下内容:

[workerMapping mapKeyPath:@"workers.firstName" toAttribute:@"firstName"];
[workerMapping mapKeyPath:@"workers.lastName" toAttribute:@"lastName"];

然后,当您运行播种时,您的工作者映射器将知道如何将people.json中的值映射到新的Worker对象。