Reputation: 697
I'm trying to create a new instance of NSManagedObjectContext so that I can perform a fetch request in a thread other than the main one. As I understand it each thread needs it's own instance although they can share stores.
My app is a core data document based app.
Having read a bit here I've got this code:
NSManagedObjectContext *managedObjectContextForThread = nil;
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
if (coordinator != nil) {
managedObjectContextForThread = [[NSManagedObjectContext alloc] init];
[managedObjectContextForThread setPersistentStoreCoordinator:coordinator];
[managedObjectContextForThread setUndoManager:nil];
}
It runs but when I perform the fetch I get no results, I suspect because the NSPersistentStoreCoordinator isn't getting setup correctly.
How should I be setting that store coordinator to work with my main store? Or is there something else I'm missing here?
Upvotes: 2
Views: 2760
Reputation: 4558
Apple's 'typically recommended approach' is to share one persistent store coordinator among contexts. Ideally you would already have a reference to your app's main managed object context, and use that context's persistent store coordinator.
NSManagedObjectContext *managedObjectContextForThread = [[NSManagedObjectContext alloc] init];;
[managedObjectContextForThread setPersistentStoreCoordinator:myMainContext.persistentStoreCoordinator];
Take a look at "Concurrency With Core Data" from Apple's Core Data Programming Guide
Upvotes: 5
Reputation: 4946
You have to add the persistent store to the store coordinator, then add the persistent store the managed object context.
if ( [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:0 URL:storeUrl options:options error:&error] ) {
managedObjectContextForThread = [[NSManagedObjectContext alloc] init];
[managedObjectContextForThread setPersistentStoreCoordinator:coordinator];
}
else {
// investigate 'error'
}
Upvotes: 0