I see that a button can have a binding for Target but can’t seem to find clear instructions for how to do that exactly. I want a button that I can programmatically point to a different subroutine as needed. Has anyone used the Target binding?
If you want to change it, don’t use bindings – just use setTarget: when you want to change it. You cal also change the action with setAction:.
This does not seem to be what the Target binding key is for. I haven’t used it myself, but according to the NSButton Binding docs (https://developer.apple.com/library/archive/documentation/Cocoa/Reference/CocoaBindingsRef/BindingsText/NSButton.html), the target binding is for:
In other words, you use it to change the object you send the selector to; you can’t use it to change the selector itself.
For example, let’s say that we have a table view populated by an array controller with (among other things) a column of buttons, and each row in the table view represents a different object in our model. We can bind that column of buttons by binding the Target to the Table Cell View, with the Model Key Path ‘objectValue’, and a Selector Name such as ‘buttonClicked:’. That way each button we click would send its action to the selector named ‘buttonClicked:’ in the object the row represents.
You could do the same thing with a single button — e.g. bind the Target key to File’s Owner with the Model Key Path ‘self.somePropertyName’ and the same Selector Name — then you could swap out the object in that property at will and have the button automatically point at the new object’s ‘buttonClicked:’ method. But nothing here lets us programmatically change the selector we are calling. If that’s the effect you want (make the button click go to a different handler), you’ll probably have to do what Shane suggested and programmatically change it at need. I mean, there’s probably some esoteric way to programmatically bind a selector this way, but I don’t know what it is, and I can’t quite see a practical use for it in any case (not when you can send the button click using a constant selector and call different handlers from there as needed).