Next: 3 Adding a Button Up: 2 Adding a Window Previous: 2.5.1 The organization of

2.6 Source Code

Here is the source code of our new application:
#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

@interface MyDelegate : NSObject
{
  NSWindow *myWindow;
}
- (void) createMenu;
- (void) createWindow;
- (void) applicationWillFinishLaunching: (NSNotification *)not;
- (void) applicationDidFinishLaunching: (NSNotification *)not;
@end

@implementation MyDelegate : NSObject 
- (void) dealloc
{
  RELEASE (myWindow);
}

- (void) createMenu
{
  NSMenu *menu;

  menu = AUTORELEASE ([NSMenu new]);

  [menu addItemWithTitle: @"Quit"  
        action: @selector (terminate:)  
        keyEquivalent: @"q"];

  [NSApp setMainMenu: menu];
}

- (void) createWindow
{
  NSRect rect = NSMakeRect (100, 100, 200, 200);
  unsigned int styleMask = NSTitledWindowMask 
                           | NSMiniaturizableWindowMask;


  myWindow = [NSWindow alloc];
  myWindow = [myWindow initWithContentRect: rect
                       styleMask: styleMask
                       backing: NSBackingStoreBuffered
                       defer: NO];
  [myWindow setTitle: @"This is a test window"];
}

- (void) applicationWillFinishLaunching: (NSNotification *)not
{
  [self createMenu];
  [self createWindow];
}

- (void) applicationDidFinishLaunching: (NSNotification *)not;
{
  [myWindow makeKeyAndOrderFront: nil];
}
@end

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

  return NSApplicationMain (argc, argv);
}
To make the code easier to read and to understand, we have moved all the code creating the menu into a createMenu method, and the code creating the window into a createWindow method.

We have also implemented the dealloc method, which is quite useless in this case, because we create only one MyDelegate object, which is only released when the application quits (there is few interest in releasing memory when the application is quitting, since all memory is going to be released anyway). But it is good programming practice to always implement dealloc; this method should release all the resources that the object was using. In this case, we only need to release the window object. Please refer to the Memory Management tutorial [yet to be written *grin*] for more information on the dealloc method.

The GNUmakefile is the usual one:

include $(GNUSTEP_MAKEFILES)/common.make

APP_NAME = WindowApp
WindowApp_OBJC_FILES = MyApp.m 

include $(GNUSTEP_MAKEFILES)/application.make



2008-01-16