需要使用RestKit创建多个相同的实体

时间:2014-08-11 17:23:19

标签: core-data restkit nsmanagedobject

我经常在RESTKit中对不同URL的多次调用下载相同的数据。第一个调用映射正常,但随后的调用将替换第一个调用的实体。

我想要的行为是让对象在其父实体中是唯一的,所以即使数据看起来相同,我仍然希望创建一个新对象,但目前看起来RESTKit希望它们是整个数据库都是唯一的。在我下载的数据中没有唯一的密钥来执行此操作,这些对象在字面上完全相同。下面是我用来创建操作的代码。如何将其设置为允许重复?

NSMutableURLRequest *request = [self requestWithURL:URL];
[request setHTTPMethod:@"GET"];

RKHTTPRequestOperation *requestOperation = [[RKHTTPRequestOperation alloc]initWithRequest:request];

RKResponseDescriptor *responseDescriptor = [INKResponseDescriptorFactory journeySegmentDescriptorForPath:URL.path inStore:[RKObjectManager sharedManager].managedObjectStore];

RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithHTTPRequestOperation:requestOperation
                                                                                               responseDescriptors:@[responseDescriptor]];

operation.managedObjectContext = [self.objectManager context];
operation.managedObjectCache = self.objectManager.managedObjectStore.managedObjectCache;
operation.savesToPersistentStore = NO;

[operation setCompletionBlockWithSuccess: ^(RKObjectRequestOperation *requestOperation, RKMappingResult *mappingResult)
{   
    success();
} failure: ^(RKObjectRequestOperation *requestOperation, NSError *error) {
    failure(error);
}];

[self.objectManager enqueueObjectRequestOperation:operation];

1 个答案:

答案 0 :(得分:0)

想出办法来做到这一点。

每次我更新数据时,即使我获得的实体包含相同的数据,我也会从不同的网址中检索它们。

RESTKit允许您从调用中检索元数据并将其映射到托管对象属性中。

所以我所做的就是将我用于请求的URL映射到一个属性中,并使用它以及一个标识符,该标识符在此调用的返回对象中是唯一的,以创建在整个数据库中唯一的对象。

所以我的映射现在看起来像这样:

RKEntityMapping *seatMapping = [RKEntityMapping mappingForEntityForName:@"Seat" inManagedObjectStore:store];
[seatMapping addAttributeMappingsFromDictionary:@{ @"designator" : @"designator",
                                                   @"status" : @"status",
                                                   @"@metadata.HTTP.request.URL" : @"requestURL"}];

seatMapping.identificationAttributes = @[@"requestURL", @"designator"];