Search code examples
objective-cmacoscocoacocoa-bindings

How to find out what object an NSControl is bound to via cocoa bindings


I'm subclassing an NSTextField so that the user can increment/ decrement the integer value with the up and down cursor keys. It works fine via its delegate, but setting the user interface state via setIntegerValue: does not update the underlying value bound via cocoa bindings.

Instead of updating the control I need to update the model, so I need to find the object that the control is bound to and the key path that is used.

I can't find anywhere how to do this, so I've overloaded the - bind:toObject:withKeyPath:options: method of my NSTextField subclass, where the binding is established and where I can see both the observed object and its key path, but surely I'm duplicating information that is already available somewhere in the control..

Is there a way of obtaining the object and key path that a control is bound to via Cocoa bindings without hacking around like this?

I'd appreciate any help.


Solution

  • Yes, there is a better way:

    - (NSDictionary *)infoForBinding:(NSString *)binding
    

    A dictionary with information about binding, or nil if the binding is not bound. The dictionary contains three key/value pairs: NSObservedObjectKey: object bound, NSObservedKeyPathKey: key path bound, NSOptionsKey: dictionary with the options and their values for the bindings.