我目前有一个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];
每个端点都提供了一种类型的所有细节以及它仅与id有关的所有关系?你想在应用程序启动时调用所有端点? – Wain
是的。目前,我对每个类型/实体都有单独的端点。由于我需要核心数据数据库来准确匹配服务器版本,我相信我需要依次调用每个端点。 –
你不能同时打电话给他们,但除此之外你应该没有问题。查看关于外键映射和获取请求块的其他答案。 – Wain