Search code examples
cocoabindingcocoa-bindings

Cocoa Bindings (Files Owner vs. App Delegate)


I just started with Cocoa Bindings and I am working on my first application.

Many samples and books use the NSArrayController but since I only want to bind a single Object and his properties to some Textfields I used the NSObjectController. I also don't have a document based application. My application is a simple one-window application.

I start to run into problems when I try to bind my NSObjectController to the Files Owner like all of the samples did. If I do this I can't compile the application. I always get an "This class is not key value compliant" error.
But if I bind the NSObjectController to the AppController instance of my application it works perfectly fine. I also managed to bind a Textfield to a field of the NSObjectController. This also works as it should.

But I don't know if I am doing the right thing. All the samples I found bind to the Files Owner - something that did not work for my App. Binding to the Application Controller seems the perfect way for a non document based Application.


Solution

  • When you bind the NSObjectController's contentObject binding, what you're doing is telling the controller how to find the object you want it to edit. This is done using Key-Value Coding, where a string is used to navigate through potentially many object relationships to locate a value. At runtime, the object controller will call [object valueForKeyPath:keyPath] using the object you've bound the controller to and the key path you've specified in Interface Builder.

    The File's Owner outlet in Interface Builder refers to the object specified as the owner when the NIB is loaded. In a document-based application, this is generally an NSWindowController. In a non-document application, the File's Owner is typically the NSApplication instance. But you didn't (and shouldn't) subclass NSApplication, so in your appilcation, File's Owner is not the right place to be looking for the object.

    Instead, you've most likely added the object to your Application Delegate, so it makes sense to bind the object controller to the Application delegate in a non-document-based application. As a suggestion, I'd go back to the previous examples you've worked through and see if you can figure out how those object controllers find their content object. Once you see the connection between the object controller and the object it controls, bindings should make a lot more sense to you.