Your First Cocoa App
The following program will open a window titled 'My First Window':
#import <Cocoa/Cocoa.h>
@interface MyWindow: NSWindow {
}
-(MyWindow*) init;
@end
@implementation MyWindow
-(MyWindow*) init {
[super init];
if( self ) {
[self setTitle: @"My First Window"];
}
return self;
}
@end
int main( int argc, char **argv ) {
NSAutoreleasePool *pool;
MyWindow *window;
/* initialise the autorelease pool */
pool = [[NSAutoreleasePool alloc] init];
/* initialise GUI and connect to WindowServer */
[NSApplication sharedApplication];
/* create the window */
window = [[MyWindow alloc] init];
/* set as window receiving keyboard events, and add it to the front */
[window makeKeyAndOrderFront: NSApp];
/* set as main window (focus) */
[window makeMainWindow];
/* start Cocoa event loop */
[NSApp run];
/* release unused objects in the pool */
[pool release];
return 0;
}
Ok what's going on here?
- #import is like #include, but makes sure every header file is included only once.
- Normally, @interface goes into the .h file, and the rest into the .m file.
- We created a simple window class, which sets its title upon initialisation.
- We can create stuff (windows) beforfe the event loop is started. Practical.
- The main window is the one with focus, the key window is the one receiving keyboard events.
- We need to create our own NSAutoreleasePool, since Cocoa assumes one exists. I'll explain this thing in the next section.
