Search code examples
objective-cxcodemacoscore-datansmanagedobjectcontext

NSManagedObjectContext passed to NSWindowController becoming nil


I'm really scratchng my head trying to work out where my managed object context is vanishing to.

I'm originally instantiating it within my app delegate and then passing it into a retained property within an NSWindowController as such:

self.TPWC = [[TestPanelWindowController alloc] initWithWindowNibName:@"TestPanel"];
self.TPWC.managedObjectContext = self.managedObjectContext;
self.TPWC.persistentStoreCoordinator = self.persistentStoreCoordinator;
[TPWC.window makeKeyAndOrderFront:nil];

I've then got a button that should instantiate an NSManagedObject and insert it into the managed object context like this:

 NSManagedObject *newInstanceOfSomeEntity =

 [NSEntityDescription insertNewObjectForEntityForName:@"SomeEntity" 
 inManagedObjectContext:self.managedObjectContext];

At this point, self.managedObjectContext has somehow become nil.

I've inserted a breakpoint into windowDidLoad and I can confirm that at that point, we do have a valid instance of an NSManagedObjectContext, but it's somehow become nil in between viewDidLoad and then trying to insert a managed object.

I've tried creating a custom initialiser to set the NSManagedObjectContext but it's still becoming nil.

Core Data is quite new to me and I'm struggling to understand what's going wrong.


Solution

  • This is not a direct answer to why you're seeing your context disappear, but it could still fix your problem:

    From an architecture standpoint, you really shouldn't be passing around the managed object context between objects, especially UI objects.

    Instead you should have a global singleton class that instantiates the managed object context (along with the coordinator and persistent store, probably), and then provide access to it via a public property. Then, from your window controller, you would just access it from the singleton object.

    (A side note if you're using multi-threading, be careful of accessing and using the same context from different threads.)