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?
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:
-windowControllerDidLoadNib:
– or if you use a custom NSWindowController subclass, in-makeWindowControllers
.-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
.