Where to get managed object context in NSPersistentDocument?

1.3k views Asked by At

It seems there's spotty information out there for using Core-data with Document based apps. I have a window controller that runs a modal window in the current document. The user enters data into a text field, which creates a mutable array of strings, which I want to use to create model objects (for a many-to-many relationship), and then save them to the core-data stack. This is the method I have in the modal window's controller.

 - (IBAction)saveContext:(id)sender {

if ([tagsArray count] != 0) {
    int objectcount;
    for (objectcount = 0; objectcount < [tagsArray count]; objectcount ++){
        Tag *singleTag = (Tag *) [NSEntityDescription insertNewObjectForEntityForName:@"Tag" inManagedObjectContext:self.managedObjectContext];
        singleTag.tagname = [tagsArray objectAtIndex:objectcount];
        singleTag.video = selectedFile;
        NSLog(@"Tagnames %@",singleTag.tagname);
        
    }
}
[NSApp stopModalWithCode:NSOKButton];
[self.window close];
}

Ok the compiler isn't happy with self.managedObjectContext. Understandably so, since this class doesn't have a context. The way I understand it, with a document based app you want to use only one MOC. What I don't understand is how to access the document's MOC. Apple's docs are a little unclear.

Getting a Managed Object Context

In OS X:

In an single-coordinator applications, you can get the application’s context directly from the application delegate.

In document-based applications, you can get the context directly from the document instance.

I'm embarrassed to say I don't know what this means. How do I get the context from the document instance? Is it some sort of global variable? Any help is greatly appreciated.

2

There are 2 answers

1
Duncan Groenewald On BEST ANSWER

When you create your Modal Window pass it the documents managedObjectContext to use.

So maybe have a property in the controller class for the modal window and set that modalWindow.moc=self.managedObjectContext prior to calling modalWindow.show or whatever you are using. Assuming self is your NSPersistentDocument subclass.

You must used the documents existing MOC, don't create a new one (you can but you don't want to go there).

The documents MOC is your definitive access point for adding objects to your Core Data store.

8
Martin R On

NSPersistentDocument has a managedObjectContext method to get its managed object context:

NSManagedObjectContext *context = [yourPersistentDocument managedObjectContext];