Next: 1.3 The run loop Up: 1 The shared application Previous: 1.1 Creating the shared

1.2 Setting a delegate for the shared NSApplication instance

Once you have learnt how to create your application's shared instance, the fastest way to develop an application is to set a delegate for your shared application object. This is done by using the method -setDelegate:, as follows:
id myObject;

// <missing: create myObject>
[NSApp setDelegate: myObject];
A delegate is an object of your choice which can customize the behaviour of your application by implementing some (predefined) methods. For example, if you want your application to display a menu (all apps should), you just need to implement in the delegate a method called
- (void) applicationWillFinishLaunching: (NSNotification *)not;
(ignore the argument for now) and put the code to create the menu inside this method. Your shared application will check if the delegate of your choice has implemented this method, and if so it will run the method just before entering the main run loop. The documentation of NSApplication lists all the other methods the delegate can implement to customize your application's behaviour; we'll learn about some of them in other tutorials.

After you set the delegate of your application object, you need to run your application; to do this, just invoke the function NSApplicationMain (), which does all for you.

To sum up, here is the code we are going to use:

#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

@interface MyDelegate : NSObject
- (void) applicationWillFinishLaunching: (NSNotification *)not;
@end

@implementation MyDelegate
- (void) applicationWillFinishLaunching: (NSNotification *)not
{
  // TODO - Create the menu here.
}
@end

int main (int argc, const char **argv)
{ 
  [NSApplication sharedApplication];
  [NSApp setDelegate: [MyDelegate new]];

  return NSApplicationMain (argc, argv);
}


Next: 1.3 The run loop Up: 1 The shared application Previous: 1.1 Creating the shared
2008-01-16