multithreadingcore-datansmanagedobjectcontextnspersistentdocument

Core Data Reading Data in Thread that's added in the Main Thread


I have a Mac document-based app, using NSPersistentDocument for the document model.

When new document is created, the app adds some default data (several sport objects and user data) to the document in the initiWithType method.

- (id)initWithType:(NSString *)typeName error:(NSError **)outError {
self = [super initWithType:typeName error:outError];

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

[[SportManagement sharedManager] addDefaultSports:managedObjectContext];
[[UserManagement sharedManager] addDefaultUser:managedObjectContext];

[managedObjectContext processPendingChanges];

return self;

}

The app has an import function that imports data from some hardware, which runs in a thread, which I set up as follows (managedObjectContext is that of the NSPersistentDocument):

dispatch_async(dispatch_get_global_queue(0, 0), ^ {

    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
    [moc setPersistentStoreCoordinator:[managedObjectContext persistentStoreCoordinator]];

Data is imported from the hardware into a number of NSManagedDataObject items. Each ManagedObject has a 'Sport' field, which needs to be populated with one of the sport objects created when the document was created.

However, none of the sport objects that were added in the - (id)initWithType:(NSString *)typeName error:(NSError **)outError exist in the new ManagedObjectContext in the thread (moc).

If I run the app, create a new document, then let the app sit idle for a minute-or-so, then try the import, then the Sport objects DO exist in the thread Managed Object Context.

How do I sync the new ManagedObjectContext in the thread with the main one from the NSPersistantDocument?

I've tried: [managedObjectContext processPendingChanges]; and [managedObjectContext setStalenessInterval];, but neither seem the solve this problem.

Interestingly, this doesn't appear to happen in Mac OS X 10.8, only in 10.7


Solution

  • Setup your "main" MOC to receive NSManagedObjectContextDidSaveNotification notifications, and merge the changes when the background MOC saves with -mergeChangesFromContextDidSaveNotification:.

    EDIT

    OK, it looks like you have made your changes in the MOC, but it is just a scratchpad. Until the data is actually saved to the persistent store, the persistent store does not know about the new data changes.

    Thus, when you create your other MOC and connect it to the PSC, it does not know about those changes.

    You can tell when autosave kicks in, because "after a while" it works.

    I would try a manual save of the document after you create the initial content.