How to automatically setup Core Data relationship when using nested contexts

前端 未结 2 1004
一向
一向 2021-02-08 08:32

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

2条回答
  •  离开以前
    2021-02-08 08:47

    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
    

提交回复
热议问题