I\'m struggling to figure out a decent solution to a problem that arises when using nested Managed Object Contexts in Core Data. Take a model that has two enites, Person and Nam
I ended up going with the convenience method solution. All the NSManagedObject subclasses in my app have a +insertInManagedObjectContext:
method. Creating instances of those objects (in my own code) is always done using that method. Inside that method, I do this:
+ (instancetype)insertInManagedObjectContext:(NSManagedObjectContext *)moc
{
MyManagedObject *result = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntityName" inManagedObjectContext:moc]
[result awakeFromCreation];
return result;
}
- (void)awakeFromCreation
{
// Do here what used to be done in -awakeFromInsert.
// Set up default relationships, etc.
}
As for the NSArrayController issue, solving that isn't bad at all. I simply created a subclass of NSArrayController, overrode -newObject
, and used that subclass for all the relevant NSArrayControllers in my app:
@implementation ORSManagedObjectsArrayController
- (id)newObject
{
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:[self entityName]
inManagedObjectContext:moc];
if (!entity) return nil;
Class class = NSClassFromString([entity managedObjectClassName]);
return [class insertInManagedObjectContext:moc];
}
@end