Can I bind one object to another and have the binding use to-many property accessor methods?

Short answer: No.

Long answer:

As well as being great for UI code, Key-Value Bindings can be terrifically helpful for just tying two objects together deeper down at the controller/model layer. I use this technique quite a bit in Sandvox, but the other day wondered if I could push it further.

Let's imagine you've got two classes declared like this:

@interface ModelObject : NSObject
											@property(copy) NSSet *foos;
											- (NSMutableSet *)mutableFoos; // will send correct KVO-notifications
											@interface ControllerObject : NSObject
											- (NSSet *)bars;
											- (void)addBarsObject:(id)object;
											- (void)removeBarsObject:(id)object;

Wouldn't it be great if you could bind bars to foos? Well you can't. Key-Value Bindings don't stretch so far as to use your -addBarsObject: and -removeBarsObject: methods. Instead, it will just call [controller setValue:foos forKeyPath:@"bars"], completely ignoring the to-many accessors!

So having found this didn't work, I resigned myself to manually setting up KVO to handle the grunt work. Or did I?

Medium answer:

What?! Are you crazy? Why would you want to do this? Apple's provided a perfectly decent NSArrayController for any binding involving a to-many relationship. Use that you numpty!

Oh. Er, yeah. It seems all too often I'm trying to bypass the use of an array controller because I don't require all of its features, yet I would be far better just starting with it and ignoring that which isn't needed in the particular case.

© Mike Abdullah 2007-2015