I'm passing some NSManagedObject data between two threads using NSOperationQueue with concurrency level to max of 1 and I'd like some suggestions on whether I'm doing this correctly.
Since NSManagedObject is not thread-safe, I'm sending in the NSManagedObjectID from ThreadA (main thread) to ThreadB via an NSOperation derived class. The general work flow:
ThreadA (main thread):
- creates NSPersistentStoreCoordinator
- creates main NSManagedObjectContext(1)
creates NSManagedObjectContext(2) for use in workerThread
creates MyNSOperationItem, passes along NSManagedObjectContext and adds MyNSOperationItem to NSOperationQueue
ThreadB (NSOperationQueue's thread):
- NSOperation derived class will retrieve data from the persistent
store using the supplied objectID.
My NSOperation class looks like this:
@interface MyNSOperationItem: NSOperation
{
// MyNSOperationItem is created in thread1 and MOC will be
// set on creation
NSManagedObjectContext *threadedMOC;
NSManagedObjectID *workItemObjectID;
}
@end
So is it okay for my NSOperation derived class to have a reference to NSManagedObjectContext or should I store the second NSManagedObjectContext elsewhere? Since this is a queue, numerous instances of MyNSOperationItem will have been created, each of them pointing to the same NSManagedObjectContext.