问题
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