Search code examples
macoscocoabindingcocoa-bindings

Why would I use NSObjectController?


Although I have searched for many information about Cocoa Bindings, I still remain relatively unsatisfied with information I have and got. It seems that topic is somewhat troublesome for many and many are just avoiding this pattern, which I believe should not be.

Of course, it may seem that bindings are sometimes too complicated or perhaps designed with too much overhead...

However, I have one very direct and specific question: Why is NSObjectController needed if I can establish bindings directly?

For example, the code:

[controller bind:@"contentObject" toObject:self withKeyPath:@"numberOfPieSlices" options:nil];

[slicesTextField bind:@"value" toObject:controller withKeyPath:@"content" options:nil];
[stepperControl bind:@"value" toObject:controller withKeyPath:@"content" options:nil];

Does exactly the same as:

[slicesTextField bind:@"value" toObject:self withKeyPath:@"numberOfPieSlices" options:nil];
    [stepperControl bind:@"value" toObject:self withKeyPath:@"numberOfPieSlices" options:nil];

In my case here, we are talking about property of the class inside which everything is happening, so I am guessing the need for NSObjectController is when:

  • key path for controller is object and binding of other controls is needed to its properties, not to its value as with primitives and wrappers around them is the case (numberOfPiesSlices in my case is NSInteger)

  • or when binding is needed from other outside objects, not only between objects within one

Can anybody confirm or reject this?


Solution

  • One of the benefits/points of bindings is to eliminate code. To that end, NSObjectController etc. have the benefit that they can be used directly in interface builder and set up with bindings to various UI elements.

    Bindings only represent part of the functionality on offer. The *ObjectController classes can also automatically take care of a lot of the other more repetitive controller (as in Model, View, Controller) code that an application usually needs. For example they can:

    • connect to your core data store and perform the necessary fetches, inserts and deletes
    • manage the undo / redo stack
    • Pick up edited but not committed changes to your UI and save them (e.g. if a window is closed while focus is still on an edited text field - this was a new one to me, I found it from mmalc's answer in the thread below).

    If you're doing none of this, then it probably isn't worth using NSObjectController. Its subclasses (NSArrayController etc) are more useful.

    Also see here for a discussion of your exact question!