2014-05-06 22 views
1

我目前有一个Core Data数据库中的实体数量与Web API后端服务JSON。每个实体在服务器上都有一个单独的端点,它返回数据库中所有这些实体,例如RestKit从外键JSON导入

.../api/student 
.../api/teacher 
.../api/degree 
etc 

JSON被序列化为包含外键id。下面是一个学生的例子回应:

[ 
    { 
    "studentID" : 1, 
    "degree" : { 
     "degreeID" : 1 
    }, 
    "name" : "My Name", 
    "teachers" : [ 
     { "teacherID" : 1 }, 
     { "teacherID" : 2 } 
    ] 
    } 
] 

的“学生,教师,度的设计是一个虚构的例子,不幸的是,真正的数据库比较复杂,有很多都“一个一对多”的和'多对多'的关系。

我是RestKit的新用户,因此无法确定以最佳方式请求和处理核心数据的这些数据。当应用程序启动时,我只需要该应用程序来更新其Core Data数据库以匹配Web API版本。任何有关如何最好地请求每个端点和处理映射的指导都将非常感激。例如,在我可以导入上面的JSON之前,我是否需要申请并存储学位和教师?我可以完全控制客户端和服务器。

编辑:增加了代码示例

下面是类似地雷一些示例代码。我已经尝试了许多不同的方法(addRelationshipMappingWithSourceKeyPath和addConnectionForRelationship例如)来处理从学生到教师的“一对多”的关系,但是我似乎总是收到以下错误:

relationship 'teachers' fault on managed object 

示例代码:

RKEntityMapping *studentMapping = [RKEntityMapping mappingForEntityForName:@"Student" inManagedObjectStore:managedObjectStore]; 

studentMapping.identificationAttributes = @[ @"id" ]; 

[studentMapping addAttributeMappingsFromDictionary:@{@"name" : @"name"}]; 

RKEntityMapping *teacherMapping = [RKEntityMapping mappingForEntityForName:@"Teacher" inManagedObjectStore:managedObjectStore]; 

tagMapping.identificationAttributes = @[ @"id" ]; 

[teacherMapping addAttributeMappingsFromDictionary:@{@"name" : @"name"}]; 

/*** RELATIONSHIP CONNECTION ***/ 

[studentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"teachers" toKeyPath:@"id" withMapping:teacherMapping]]; 

/*** RESPONSE DESCRIPTORS ***/ 

RKResponseDescriptor *studentResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:studentMapping method:RKRequestMethodGET pathPattern:@"/api/student" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 

[objectManager addResponseDescriptor:studentResponseDescriptor]; 

RKResponseDescriptor *teacherResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:teacherMapping method:RKRequestMethodGET pathPattern:@"/api/teacher" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 

[objectManager addResponseDescriptor:teacherResponseDescriptor]; 
+0

每个端点都提供了一种类型的所有细节以及它仅与id有关的所有关系?你想在应用程序启动时调用所有端点? – Wain

+0

是的。目前,我对每个类型/实体都有单独的端点。由于我需要核心数据数据库来准确匹配服务器版本,我相信我需要依次调用每个端点。 –

+1

你不能同时打电话给他们,但除此之外你应该没有问题。查看关于外键映射和获取请求块的其他答案。 – Wain

回答

1

处理每个响应时将与现有对象建立关系。不存在的对象默认情况下会被忽略。

您可以有多个响应描述符来创建存根对象,以便创建关系并在随后填充对象的详细信息。

通常,我会有一个请求,以非常少的细节获取“所有”的结构/关系,然后在用户请求时填写详细信息。

+0

谢谢@Wain - 我已经做了一些更多的研究,看起来存根方法会很好地工作。不幸的是,我在RestKit中识别外键“一对多”关系时遇到了一些麻烦。我已经为这个问题添加了一些示例代码,如果你愿意快速浏览一下,:-) –

+0

故障不是一个错误,它只是(潜在的)内容尚未载入内存(尚)。 – Wain