NSButton *myButton; id myObject; // <missing code: create myButton, myObject etc> [myButton setAction: @selector (terminate:)]; [myButton setTarget: NSApp];When the user presses myButton, the gui library sends the terminate: message to the object NSApp, passing as argument myButton, executing the equivalent of the following code:
[NSApp terminate: myButton];This way, when the user clicks the button, the application quits.
The button which was clicked is passed as an argument to the action so that the receiving object can determine (if needed) which button was actually pressed, so that the same method may be used for more than one button. In our case, NSApp simply discards the argument of terminate:.
In brief, the action is the method to be invoked when the user clicks on the button; the target is the object on which to invoke the method. action should be a selector for a method returning void and taking a single argument (of type id, a generic object). The button which was clicked is passed as an argument to the invocation of action on the target.
The case of a menu item is completely similar. When the user selects this menu item, the gui library performs the menu item action (terminate: in this case) on the menu item target. The argument passed to terminate: is the menu item which was selected.
Usually, no target is specified for a menu item, as in our code
[menu addItemWithTitle: @"Quit"
action: @selector (terminate:)
keyEquivalent: @"q"];
which only specifies that the action is terminate:. When no
target is specified, the gui library tries to determine an appropriate
target dynamically at run-time. For now the only important thing to
know is that the gui library will try to send the action to certain
objects (roughly, the objects inside a window which have the input
focus) and, failing these objects, it will try to send the action to
NSApp, and as a last resort to NSApp's delegate. In
our example, we want the action terminate: to be sent to
NSApp (thus terminating the application when the user selects
the Quit menu item), so this automatic mechanism works just
fine for us (actually, you will soon discover that this automatic
mechanism works fine extremely often). So, we don't need to set
explicitly a target for our menu item.