문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

NSManagedObjectContext *context = [yourPersistentDocument managedObjectContext];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top