我尝试保存到从服务器获取的Core Data NSManagedObject。但我不知道如何将success block
中[mappedResult firstObject]的对象保存到Core Data。我怎样才能做到这一点?我应该使用RKObjectManager's postObject
还是RKManagedRequestOperation
?我应该在此之前做[managedObjectContext insertNewObjectForEntityForName:@""]
吗?在这个案例的官方文档中找不到任何指示,需要一些帮助。
**编辑:**我这样初始化RKManagedRequestOperation
:
RKResponseDescriptor* responseDescriptor =[RKResponseDescriptor
responseDescriptorWithMapping:[UserMapping mappingForUser]
method:RKRequestMethodPOST
pathPattern:kUserEndpoint
keyPath:@"profile"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKRequestDescriptor* requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[UserMapping mappingForUserProfileModel]
objectClass:[User class] rootKeyPath:@"profile" method:RKRequestMethodPOST];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
userObject = [User new];
NSDictionary* userParameters = @{ @"user_id" : [User sharedUser].userId};
[[RKObjectManager sharedManager] appropriateObjectRequestOperationWithObject:resumeObject method:RKRequestMethodPOST
path:kUserEndpoint
parameters:userParameters];
RKManagedObjectRequestOperation* managedRequest = [[RKManagedObjectRequestOperation alloc]
initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kService, kUserEndpoint]]]
responseDescriptors:@[responseDescriptor]];
managedRequest.managedObjectContext = _managedObjectContext;
[managedRequest setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"MAPPING = %@", [mappingResult firstObject]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
[[RKObjectManager sharedManager] enqueueObjectRequestOperation:managedRequest];
EDIT2: RestKit不会将映射数据保存到CoreData。但userObject.title完美保存:
userObject = [_managedObjectContext insertNewObjectForEntityForName:@"User"];
userObject.title = @"USER_NAME";
NSDictionary* userParameters = @{ @"user_id" : [User sharedUser].userId};
[[RKObjectManager sharedManager] postObject:userObject path:kUserEndpoint parameters:userParameters
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
} failure:^(RKObjectRequestOperation *operation, NSError *error) { }];
答案 0 :(得分:3)
你需要退后一步,因为你的建议是在黑暗中拍摄。
如果使用托管对象库配置对象管理器并使用实体映射创建响应描述符,那么当您因请求而接收数据时,它将转换为托管对象。在调用成功块之前,这些对象将自动保存到核心数据存储中。
您可以照常创建要创建的任何其他对象,并且需要显式保存上下文。
使用RestKit发送请求本身不会更改商店内容,只有响应会导致更改。
答案 1 :(得分:2)
参见本教程。有一个使用RestKit与对象管理和代码数据
的例子