2
votes

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?

2

2 Answers

5
votes

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

0
votes

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'
}