So I need to use cora-data managed object context using multiple thread. I found the below implementation to be pretty much what I need. I have 2 question :
Where do I release the MOC that I allocate ? I don't want to go through every function thread in my app and to call a function to release the MOC. I'd rather write the function, and somehow make it so it be called by every thread prior to his exit. is that possible ?
Is the below implementation enough for core data concurrency ?
-(void) StoreManagedObjectContextF开发者_如何学PythonorCurrentThread:(NSManagedObjectContext*) context { [[[NSThread currentThread] threadDictionary] setObject: context forKey: AQPerThreadManagedObjectContext]; } -(NSManagedObjectContext *) myManagedObjectContext { NSManagedObjectContext * result = [[[NSThread currentThread] threadDictionary] objectForKey: AQPerThreadManagedObjectContext]; if ( result != nil ) return result; NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator!=nil) { NSManagedObjectContext * moc = [[NSManagedObjectContext alloc] init]; [moc setMergePolicy: NSMergeByPropertyObjectTrumpMergePolicy]; [moc setPersistentStoreCoordinator: coordinator]; [self StoreManagedObjectContextForCurrentThread:moc]; [moc release]; // now owned by the thread dictionary return moc; } return nil; }
In the implementation you've provided, you haven't got a way to release the managed object context before the thread disappears, because its lifetime is dictated by the thread dictionary, and that object's lifetime is handled by Foundation, not by you.
If you want to manage the objects' lifetimes, you need to manage their storage. That means moving away from using -threadDictionary
. One option is to implement your background work as NSOperation
subclasses and keep the managed object contexts around for the lifetime of the operations, but that's likely a big change from what you currently have.
精彩评论