Search code examples
objective-ccocoacore-datacocoa-bindings

Cocoa Cannot perform operation without a managed object context


I have a Mac window based application using CoreData and Cocoa bindings to bind a CoreData entity to an NSArrayController for displaying in a NSCollectionView.

I have a property on my controller (which is set as the views Files Owner) called managedObjectConext. In the awakeFromNib method I have tried setting the managedObjectContext (MOC) property to:

managedObjectContext = [(MyApplicationAppDelegate *)[[NSApplication sharedApplication] delegate] managedObjectContext];
managedObjectContext = [[NSApp delegate] managedObjectContext];

I have also configured the NSArrayControllers MOC bindings to the 'Files Owner' MOC property and attribute bindings to that of my CoreData entity.

However everytime I run the application just before its about to do the binding I get the follwowing error message:

Cocoa Cannot perform operation without a managed object context

I have logged in the console to check that the MOC is not nil, which I presume it isn't as this is the NSLog from the MOC object: myMoc = NSManagedObjectContext: 0x10052f9c0

I am totally stumped now and frustrated that something that should be so simple has taken up so much of my time! Any help would be greatly appreciated.


Solution

  • Bindings are defined in the nib, so if the nib doesn't know about the managedObjectContext property of the controller, then the bindings don't either.

    In the interface editor, you need to bind the managedObjectContext key in the array controller's bindings panel to the specific context.

    The easiest way to do this for a one context app, is to label the managedObjectContext property in the app delegate as an IBOutlet so that it shows up in the interface editor. Then just bind it directly from the array controller's panel.

    Honestly, I don't know why they don't do that in the Xcode template itself. You end up doing it so often.