实际上,我使用的是RestKit 0.22。
在我的代码中,我添加了对象映射:
RKEntityMapping *materialMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Material class])
inManagedObjectStore:[RKObjectManager sharedManager].managedObjectStore];
...
RKResponseDescriptor *responseMaterialsDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:materialMapping
method:RKRequestMethodGET
pathPattern:urlMaterials
keyPath:kRestApiMAterialsKeyPath
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseMaterialsDescriptor];
通常这段代码工作正常,请求正确的url后我得到正确的响应并将对象存储到本地数据库。
现在我想要请求相同的url但是在将JSON响应映射到Material对象之后不将结果存储到数据库。我想在经过一些修改后插入所有项目。您有什么建议我如何通过RestKit避免将对象存储/保存到数据库?
答案 0 :(得分:2)
如果您希望在映射后添加一些属性或修改现有属性,那么您应该使用mappingMetadata并从中创建responseDescriptors。
[materialMapping addAttributeMappingsFromDictionary:@{@"@metadata.property1": @"property1", @"@metadata.property2": @"property2"}];
RKResponseDescriptor *materialResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:materialResponseDescriptor pathPattern:@"somPath" keyPath:@"" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
然后将响应描述符添加到 RKObjectManager 并创建 RKManagedObjectRequestOperation 以从远程URL获取
RKRoute *route = [[[[RKObjectManager sharedManager] router] routeSet] routeForName:routeName];
[self cancelAllRequestWithMethod:route.method matchingPath:route.pathPattern];
NSMutableURLRequest *request = [_objectManager requestWithPathForRouteNamed:routeName object:nil parameters:nil];
RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:[[RKObjectManager sharedManager] responseDescriptors]];
operation.managedObjectContext = [RKManagedObjectStore defaultStore].persistentStoreManagedObjectContext;
operation.managedObjectCache = [RKManagedObjectStore defaultStore].managedObjectCache;
operation.savesToPersistentStore = YES;
现在,设置映射元数据即。这是映射完成时将映射到原始属性的值,
[operation setMappingMetadata:@{@"property1": value1, @"property2": value2}];
然后,排队操作,它应该将自定义值映射到属性。注意,property1和property是实体中的属性,您不为它创建responseDescriptor。
[[RKObjectManager sharedManager] enqueueOperation:operation];