I’m working on a very complex iPad app which may run about 10 separate threads. Each thread performs some data IO operation using Core Data. I’m trying to come up with a simple and elegant solution to simplify the merging process.
Backstory
My app uses what I refer to as an engine. My app may have many engines. Each engine runs in a continuous interval each with a specific goal: Clean up, fetching and merging RSS, fetching and merging theme changes, fetching and merging documents. Each engine runs in its own thread, each with its own managed object context.
Question
Rather than observing NSManagedObjectContextDidSaveNotification in each of the engines, I came up with the idea to derive from the NSManagedObjectContext class and have IT observe/merge the changes.
Does anyone know of any gotchas or issues surrounding this method?
Here is a rough example of what it might look like:
.h
@interface SelfMergingManagedObjectContext : NSManagedObjctContext
@end
.m
@interface SelfMergingManagedObjectContext()
-(void)observeDidSaveNotification;
@end
@implementation SelfMergingManagedObjectContext
-(id)initWithConcurrencyType:(NSManagedObjectContextConcurrencyType)ct
{
..
..
..
[self observeDidSaveNotification];
return self;
}
-(id)init
{
..
..
..
[self observeDidSaveNotification];
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
..
..
..
[self observeDidSaveNotification];
return self;
}
-(void)observeDidSaveNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:nil];
}
-(void)contextDidSave:(NSNotification *)notif
{
[self mergeChangesFromContextDidSaveNotification:notif];
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end
Usually that kind of thing is done as a category on NSManagedObjectContext. I don’t see any problems off the top of my head with the extension approach, so long as you are always making the managed object contexts you will use to get the right type.
A heads up on using multiple managed object contexts – make sure to set a merge policy for the managed object context on the main thread, the default will throw exceptions on merges. Also try to keep the possible merges VERY small.