Is ThreadedCoreData example (from Apple) creating NSManagedObjectContext on main thread?
You must create the managed context on the thread on which is will be used. If you use NSOperation, note that its init method is invoked on the same thread as the caller. You must not, therefore, create a managed object context for the queue in the queue’s init method, otherwise it is associated with the caller’s thread. Instead, you should create the context in main (for a serial queue) or start (for a concurrent queue).
In ConnectionDidLoading method:
ParseOperation *parseOperation = [[ParseOperation alloc] initWithData:self.earthquakeData]; [self.parseQueue addOperation:parseOperation]; [parseOperation release]; // once added to the NSOperationQueue it's retained, we don't need it anymore
ConnectionDidiLoading is being called on the main thread. Now Inside the ParseOperation::initWIthData method we have something like this : (See ParseOperation.m file)
// setup our Core Data scratch pad and persistent store managedObjectContext = [[NSManagedObjectContext alloc] init]; [self.managedObjectContext setUndoManager:nil]; SeismicXMLAppDelegate *appDelegate = (SeismicXMLAppDelegate *)[[UIApplication sharedApplication] delegate]; [self.managedObjectContext setPersistentStoreCoordinator:appDelegate.persistentStoreCoordinator];
My understanding is that this managedObjectContext is still created on the main thread.
Would appreciate if someone clarify or correct my understanding as it is quite unlikely that sample code from Apple is not correct.
Good point here. Seems the code is not correct (but maybe I'm wrong). Based on my experience you should create the context within the start method (for example) or something strange could happen.
The other rule is that you cannot pass NSManagedObject among treads. Pass NSManagedObjectID instead. Before passing them, you need to save to disk.
These rules habe been enforced in iOS 5. Starting from iOS 5 you could take advantage of Core Data new API for creating context in a private queue (there is also a main queue) and perform long running calculation there. In addition if you pass NSManagedObject between threads exceptions occur.
In my opinion you are correct. Apple seems to break their own rules in this sample code. However it seems in practice, and this is not much advertised, that as long as the managed object context is used only on one single thread, you are safe, regardless on which thread the context was created.