I am running into intermittent, hard-to-reproduce errors on my iPhone app, so I am checking my assumptions around concurrency.
Running AFNetworking v0.10.x, I have the following network call:
[self postPath:@"/myEndPoint"
parameters:params
success:^(AFHTTPRequestOperation *request, id response)
{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
// do stuff with object context here
[appDelegate.objectContext save];
}
]
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
// do other stuff with object context
[appDelegate.objectContext save];
In my AppDelegate:
-(NSManagedObjectContext*) objectContext
{
if(nil == _objectContext)
{
... set up sqlite persistent store coordinator and object model ...
_objectContext = [[NSManagedObjectContext alloc] init];
[_objectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
[_objectContext setMergePolicy:NSOverwriteMergePolicy];
}
return _objectContext;
}
Is it possible, in this scenario, to end up with concurrency problems? Or, in other words, is AFNetworking's API thread-safe? I thought the NSOverwriteMergePolicy would cover me for conflicts, but crashing persists (albeit intermittently).
AFNetworking's callbacks are executed on the main thread. As a result, they are 'thread-safe', because there is only one thread that is interacting with CoreData. If you only have a single managed object things will be straightforward.
From Apple:
Tasks added to this queue are performed serially on the main thread itself. Therefore, you can use this queue as a synchronization point for work being done in other parts of your application.
There are still lots of considerations when using multi-threaded CoreData and multiple managed object contexts, and for those I refer you to rsswtmr's excellent answer, which doesn't correctly answer my question, but provides links to lots of good information.