Reputation: 4820
Consider the following piece of code which is a simple request to get user data for a particular username.
- (void)updateInformation
{
AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager sharedManager];
NSDictionary *params = @{@"username": self.username};
AFHTTPRequestOperation *operation = <create_op>
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id response){
// use response to populate user
// self.fullname = response[@"fullname"];
}failure:nil];
[httpManager.operationQueue addOperation:operation];
}
This code is part of a category for a particular entity for e.g. User
.
Now usually this method is called in a scheduleBlock
. scheduleBlock
(http://cocoadocs.org/docsets/XMPPFramework/3.6.1/Classes/XMPPCoreDataStorage.html#//api/name/scheduleBlock:):
This method asynchronously invokes the given block (dispatch_async) on the storageQueue.
Now my question is simple — the request response is received in a different thread as compared to the storageQueue
on which the updateInformation
method is actually called => there needs to be a different managed object context that needs to be created to store the object and then sync those changes with the context for the storage queue. Is this right?
Another question is — is there a better way of handling this, i.e. not creating a new context and trying to sync it with the storage queue context?
Upvotes: 0
Views: 65
Reputation: 46728
You can use the same context but since you are coming in from another thread/queue then you will need to wrap the Core Data processing code in a performBlock:
or performBlockAndWait:
so that the processing is done on the correct thread that is associated with the context.
Upvotes: 1