I’m trying to set up a fairly simple view that presents a table to the user. This table is connected to an Array Controller, which I want to use to retrieve records from Core Data. For some reason, I can’t seem to connect the ‘managedObjectContext’ outlet to anything else in my app. When I created my project, there was a property generated in my app delegate which returns the MOC I need, but I can’t hook it up in Interface Builder, even after prepending “IBOutlet” to the declaration. Image below showing the available connection on both ends:
http://yada.im/uploads/image/screenshot/1108/7efebc90ca7187a537da9ae003dd5f3e.png
I’m sure that I’m missing some simple step here but I can’t tell what piece of glue code I’m supposed to write that will allow me to hook this up more easily. For reference, I’ve tried dragging a line from the controller’s moc outlet to every single source I could think of, and changed the “File’s Owner” class to that of my application. Stumped here!
Typically in the template provided by XCode the
managedObjectContextcomes along withAppDelegate.You have to bind the
managedObjectContextreference of the array controller to themanagedObjectContextinAppDelegate.For this you have to make an object of
AppDelegateinside the xib i.e., if its not already present.(Drag an object placeholder from your object library and make its class asAppDelegate)This makes
AppDelegatevisible for binding inside that xib.Next step is actually binding the managedObjectContext. Select your array controller and go to bindings inspector. In the parameters section select App Delegate from the drop down and check on “Bind to”.
Fill the “Model Key Path” field with
self.managedObjectContext. Now you will find the connection in the connections inspector also.UPDATE:
The process of creating a new
AppDelegateobject is to be done only if it is not already present in the main nib file (but the stub generated always has theAppDelegateobject in the main nib file).For a non main nib file, if we follow the above approach, a new
AppDelegateobject will be created which won’t be theNSApplication'sdelegate. Even though this can be solved by connecting delegate outlet of the application object proxy provided in each nib, theAppDelegateobject still won’t be the same.The result is two different managedObjectContext talking to the same store. Although this might appear to work properly when the changes are saved at each step, this is not what we want.
To get the right AppDelegate object, i.e. the one used in the main nib file:
-instead of creating a new
AppDelegateobject, bind themanagedObjectContextof the array controller directly through the application to its delegate. In other words the object to bind to will be the application object and the key path used will beself.delegate.managedObjectContext.