Implementing Callbacks in Macintosh Applications
Macintosh application development uses callbacks to allow Mac OS X to execute code within your app for specific operations. If you’re creating a standard Macintosh window- or document-based app, the very first code that OS X will execute is in one of the following callback methods you have to create for your app, depending on the app design:
Window-based apps: (void)applicationDidFinishLaunching:(NSNotification*)aNotification
Document-based apps: (void)windowControllerDidLoadNib:(NSWindowController*)windowController
A callback is simply a method that the OS eventually executes while it’s trying to supply or retrieve information from your app. Your application code will execute a method for a Cocoa class where your app will have the opportunity to provide the name of a method of one of your classes, to be called on an object of that class your app will also have to provide.
A delegate is a helper object, which a Cocoa class uses to extend the functionality of the class by allowing you to implement code which the Cocoa class will execute in certain circumstances. A Cocoa class checks its delegate object (if one has been assigned) for whether the delegate provides an implementation of a specific method. If the delegate has that method, the Cocoa class executes that method; if the delegate doesn’t implement that specific method, the Cocoa class either uses a default method of its own or logs an error. Most delegates must incorporate a particular protocol that determines what methods they may implement; your code’s delegates must use the implement methods from the specific protocol that the delegate expects.
Here are some of the Cocoa objects that can use delegates to execute your code:
NSTableView. The NSTableView accepts a delegate that obeys the NSTableViewDelegate protocol. This includes 20 to 30 methods that your app’s delegate object can implement to support your app’s need to know what the NSTableView is doing. There are methods that will be called in your application when it needs to know and react to an actions, such as when a user makes a selection in the table or when a column is resized.
NSApplication. You can assign an NSApplicationDelegate to handle some of the methods that an NSApplication instance (your application) will receive. These methods may be called just before or just after your application executes another method, so that your app can be prepared.
NSWindow. An NSWindowDelegate assigned to one of your application’s windows will give your app a chance to respond to a user resizing, moving, or other window events.
NSMenu. You implement an NSMenuDelegate to support events that happen when a user interacts with menus in your application.