经过长时间的研究,我正在写这篇文章,但我真的很难找到解决我问题的最佳方法。
我对 resKit 和 CoreData 都很陌生......无论如何,我正在映射并保存我从 Web 服务接收到的 JSON 数据。
这里有一些代码:
//ResKit and Core Data initialization here
...
//Initialization RKObjectManager
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://http://www.myWebService.com"]];
objectManager.managedObjectStore = managedObjectStore;
[RKObjectManager setSharedManager:objectManager];
//Categories Mapping and descriptor
RKEntityMapping *categoriesMapping = [RKEntityMapping mappingForEntityForName:@"XNCategory" inManagedObjectStore:managedObjectStore];
[categoriesMapping addAttributeMappingsFromDictionary:@{
@"id": @"idCategory",
@"desc": @"desc",
@"idFam":@"idFam"}];
categoriesMapping.identificationAttributes = @[ @"idCategory" ];
RKResponseDescriptor *categoriesDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:categoriesMapping
method:RKRequestMethodGET pathPattern:@"getData.asp" keyPath:@"categories"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
//Families Mapping and descriptor
RKEntityMapping *familiesMapping = [RKEntityMapping mappingForEntityForName:@"XNFamily" inManagedObjectStore:managedObjectStore];
[familiesMapping addAttributeMappingsFromDictionary:@{
@"id": @"idFam",
@"desc": @"desc"}];
familiesMapping.identificationAttributes = @[ @"idFam" ];
RKResponseDescriptor *familiesDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:familiesMapping
method:RKRequestMethodGET pathPattern:@"getData.asp" keyPath:@"families"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
//Relation between the 2 mapping
NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"XNCategory"
inManagedObjectContext:[managedObjectStore mainQueueManagedObjectContext]];
NSRelationshipDescription *userRelationshipFrom = [categoryEntity relationshipsByName][@"family"];
RKConnectionDescription *connectionUserMessageFrom = [[RKConnectionDescription alloc]
initWithRelationship:userRelationshipFrom attributes:@{ @"idFam": @"idFam" }];
[categoriesMapping addConnection:connectionUserMessageFrom];
//Finally add the descriptor to the object manager
[objectManager addResponseDescriptor:categoriesDescriptor];
[objectManager addResponseDescriptor:familiesDescriptor];
在另一个视图控制器中,当我需要下载所有数据时,我只需:
[[RKObjectManager sharedManager] getObjectsAtPath:@"getData.asp" parameters:@{kAuthKeyName : kAuthKeyValue} success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
//Success block
}failure:^(RKObjectRequestOperation *operation, NSError *error) {
//Failure Block
}];
此代码正确下载并自动保存到 CoreData 中的持久存储中,保留实体之间的关系。
现在我的问题是:有什么方法可以避免这种自动保存吗?因为我需要处理从 webService 检索到的数据,并且只有在我决定时才保存它们。
我发现这篇文章非常有用,或者至少给了我一个很好的开始研究的输入:Best practice for temporary objects in RestKit with Core Data,但这是 2012 年的一篇文章,我不知道是否发生了变化现在有一个更好的解决方案。
换句话说,我需要的是一种允许使用 ResKit 进行映射的方法,因此,所有接收到的数据都将根据我创建的所有NSRelationshipDescription进行正确的实体映射,并手动管理该保存到持久存储。
非常感谢您的耐心和帮助。