I read Marcus Zarra’s chapter on multithreading in my book Basic Data and looked rather closely at its sample code. But his code and others that I found elsewhere seem to be concentrated in background processes that shouldn't know about each other. These examples are good for importing a tree structure, but they do not affect the import of a more general (complex) structure, such as a directed acyclic graph.
In my case, I am trying to analyze the hierarchy of C ++ classes and would like to use as many NSOperations as possible. I would like to create an instance of NSManagedObject for each class I encounter, and I would like to combine different NSManagedObjectContexts every time it is saved.
Aside: I can get everything to work with one NSOperation, which iterates through the files and parses them one at a time. This implementation uses the -mergeChanges method: an approach that calls -mergeChangesFromContextDidSaveNotification: on the main thread, MOC works well.
But ideally, I would have one NSOperation, iterate over the source files and run NSOperations to parse each file. I tried several approaches - but it seems that not everything is correct. Most promising was that every NSOperation observe NSManagedObjectContextDidSaveNotification. With -mergeChanges: looks like this:
- (void) mergeChanges:(NSNotification *)notification
{
if ([notification object] == [self managedObjectContext])
{
AppDelegate *appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate];
NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];
[mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
return;
}
[self setNeedsToMerge:YES];
[self setMergeNotification:notification];
}
, NSOperation main() ivar 'needsToMerge' . , -mergeChangesFromContextDidSaveNotification: MOC NSNotifications. requireToMerge reset. , , -mergeChangesFromContextDidSaveNotification: MOC.
, , :
: - objc .
NSPeristentStoreCoordinator - , NSManagedObjectContext -save: -save: -mergeChangesFromContextDidSaveNotification: , PSC.
, .