For the More Curious: Setting the Target Programmatically

NSControl includes the property:

v​a​r​ ​a​c​t​i​o​n​:​ ​S​e​l​e​c​t​o​r​

Notice that the action property is a selector, so to set the action of a control programmatically, you need to create a selector. For example, suppose you had a button playButton and a method play:

 ​ ​v​a​r​ ​p​l​a​y​B​u​t​t​o​n​:​ ​N​S​B​u​t​t​o​n​

 ​ ​f​u​n​c​ ​p​l​a​y​(​s​e​n​d​e​r​:​ ​N​S​B​u​t​t​o​n​)​ ​{​
 ​ ​ ​ ​ ​ ​.​.​.​
 ​ ​}​

To set playButton’s action to be play, you would write:

 ​ ​l​e​t​ ​p​l​a​y​S​e​l​e​c​t​o​r​ ​=​ ​S​e​l​e​c​t​o​r​(​"​p​l​a​y​:​"​)​
 ​ ​p​l​a​y​B​u​t​t​o​n​.​a​c​t​i​o​n​ ​=​ ​p​l​a​y​S​e​l​e​c​t​o​r​

The first line initializes a Selector with the string "play:" ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.