RestKit – 发布对象并更新其属性

我有一个使用RestKit和Sinatra支持的服务器的小应用程序。 当我将用户对象发布到服务器时,服务器成功保存用户并使用新创建的用户的json表示进行响应。

这是在客户端上创建用户的代码:

User *currentUser = [User currentUser]; currentUser.email = @"jacob@mail.com"; currentUser.firstName = @"Jacob"; currentUser.lastName = @"Morris"; currentUser.phone = @"2088956709"; currentUser.deviceId = @"MY-DEVICE-ID"; currentUser.password = @"password"; currentUser.passwordConfirmation = @"password"; currentUser.timeStamp = [NSNumber numberWithFloat:3987987987.12233]; //totally random RKSpecResponseLoader *loader = [RKSpecResponseLoader responseLoader]; [dataController.rkObjectManager postObject:currentUser mapResponseWith:[User rkObjectMapping] delegate:loader]; [loader waitForResponse]; NSLog(@"Current user id is now: %@", currentUser.userId); STAssertTrue([loader success], @"response from server should be a success"); 

从服务器返回的响应如下所示:

"{\"user\":{\"deviceId\":\"MY-DEVICE-ID\",\"email\":\"jacob@mail.com\",\"userId\":5,\"lastName\":\"Morris\",\"phone\":\"\",\"timeStamp\":3987987968.0}}"

服务器负责在成功创建对象时分配userId 。 当响应返回时,我希望在客户端更新currentUser对象。 我认为它应该是可能的,因为我将对已发布对象的引用传递给对象加载器。 如何在成功响应后让对象加载器更新userId? (我希望能够在不必捕获响应本身的情况下执行此操作。)

是什么让你认为postObject成功后新的User对象没有被更新?

我的理解是,当你使用postObject时,在RKObjectLoader中它会尝试将响应映射回POST为默认行为的原始对象。 让它不能做到的唯一方法就是你向目标对象收费。

尝试这样的事情:

 [[RKObjectManager sharedManager] postObject: currentUser delegate:self block:^(RKObjectLoader* loader) { loader.resourcePath = @"/users"; loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"/users"]; }]; 

只要您正确设置了映射(从服务器进入objc模型,从objc模型到服务器)并且正确设置了KeyPath(是json {user:{user stuff}}或者只是{用户的东西})那么它应该“正常工作”。