Wednesday, September 21, 2011

Simple GUI Hello World Using Cocoa

First of all, you must install Xcode --- if you haven't do that already, so that you'll be able to compile the following codes.

After you have everything about the tools ready, then you can create a new plain text file using any text editor (preferably the one with Syntax Highlighting capability for C/C++ language and their variants, including Objective-C/C++). In this case I'm using Xcode editor, but for now we're not using any other Xcode's features other than just editing text with fancy highlighting and of course the GCC compiler for Mac OS X, which already attached to the system after the installation of Xcode.

Open a terminal (that's from /Applications/Utilities/Terminal.app), then change directory into your preferred place for this test --- any place will do, maybe some new folder on your Desktop. Type ' cd ~/Desktop ', then 'touch test1.m' to create this new file.

Actually you can use Xcode's menu File->New File... for this, but I don't want you to be confused by the next options following the menu.

Either way, open that new test1.m by just double-clicking the icon from the Finder, then type the following lines of codes.  

/*
 test1.m
 Compile using gcc -framework Cocoa -o Test1 test1.m
 Then execute these lines of commands:
   mkdir -pv Test1.app/Contents/MacOS
   mv -v Test1 Test1.app/Contents/MacOS
 You can then double-click the icon of Test1.app from Finder window, or just
 from Terminal using ' open Test1.app '
 */

#include <Cocoa/Cocoa.h>

int main(int argc, const char** argv)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[NSApplication sharedApplication];
NSRunAlertPanel(@"Testing Message Box",
@"Hello, World!",
@"OK", NULL, NULL);
[pool release];
return 0;
}

You can also copy-paste the text if you like, but I recommend you to type them yourself, because that way you will be forced to memorize each lines, which is a good practice.

You can then execute the above command lines (just 3 lines including the compilations and packaging your new application) --- that's the one I commented out on the top of this sample text codes.

If there's no mistyping or any other mistakes, the application should run nicely, showing a MessageBox similar to the following picture:

Test1.app running.

Congratulation, and welcome to the Mac OS X's GUI programming!

Examine your first application codes, and try to change the strings for parameters sent to NSRunAlertPanel().


1 comment:

  1. Hi,

    Thanks for your excellent message box example using C - works great.

    Do you have any examples of adding an icon to the menu bar using just C?

    Thanks again,

    Dan

    ReplyDelete