Search code examples
cocoacore-datanspersistentdocument

Is -makeWindowControllers the best place to initialize an NSPersistentDocument?


When loading an existing document using NSPersistentDocument, as part of initialization I'd like to prepare some content:

    NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"DocumentRoot"];
    NSArray *results = [self.managedObjectContext executeFetchRequest:req error:NULL];
    if (results.count) self._docRoot = [results objectAtIndex:0];

When I put this code in -init, the fetch request doesn't return any results.

I encountered this problem while refactoring the view-controller components from my NSPersistentDocument subclass to a new NSWindowController subclass. I used to handle this initialization in -windowControllerDidLoadNib:, but that isn't called anymore.

If I move the code from -init to -makeWindowControllers I get the results I expect. Is -makeWindowControllers really the right place to prepare content like this?


Solution

  • Based on the responses I've gotten I think I'm doing the right thing, so here's my answer to my own question.

    If you're using the Core Data stack provided by NSPersistentDocument, you can not use Core Data in -init.

    Instead, you should:

    1. Put the document-initialization code directly in -windowControllerDidLoadNib: – or if you use a custom NSWindowController subclass, in -makeWindowControllers.
    2. You may also abstract the document-initialization code into a helper method with some unique name like -setUpDocument, and call that method from -makeWindowControllers/-windowControllerDidLoadNib: instead.

    If you're using a plain NSDocument, or you're setting up the Core Data stack on your own, you can set up the document model in -init.