RestKit - Post object and update its attributes

核能气质少年 提交于 2019-12-13 14:52:59

问题


I have a small app using RestKit with a Sinatra-backed server. When I post a user object to the server, the server successfully saves the user and responds with a json representation of the newly created user.

Here's the code to create a user on the client:

  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");

The response coming back from the server looks like this:

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

The server is responsible for assigning the userId upon successful creation of the object. When the response comes back, I'd like the currentUser object be updated on the client side. I'm thinking it should be possible since I'm passing a reference to the posted object to the object loader. How can I get the object loader to update the userId upon a successful response? (I'd like to be able to do this without having to capture the response itself.)


回答1:


What makes you think the new User object isn't being updated once the postObject is successful?

My understanding if when you postObject, in the RKObjectLoader it will try to map the response back to the original object being POST'd as default behavior. The only way to get it to not do it is if you bill out the target object.

Try something like this:

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

As long as you have the mappings setup correctly (coming from the server into the objc-model and the from objc-model to server) and you have your KeyPath setup correctly (is the json { user : { user stuff} } or just { user stuff } ) then it should "just work".



来源:https://stackoverflow.com/questions/8717407/restkit-post-object-and-update-its-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!