Hello World for a Mac Cocoa Console Application in Cocoa
Mar 21

I started reading a book for Cocoa. It’s good to start with some application which can take you from a program that sets values or gets it to manipulate something. Hello World stop your curiosity but that doesn’t give you next steps.

I am building a program which can take current time as seed and generate random numbers. Also, i explored this awakeFromNib function which is kind of Page_Load or Init() routine. This will be exected automatically to provide your app a chance to initialize values.

Step 1: Create a new Project as “Cocoa Application” and name it as “RandomNumberGenerator”

Step 2: Create a new Class called MyController.m/h

Step 3: Open MainMenu.nib and make an interface to look like the following:

Step 4: Create a new Object in yor MainMenu.nib window as shown below (pick up the NSObject from the Library)Step 5: Rename the object to MyController and add actions and outlets as shown below:

Note: Mac OS X treats UI to depict MVC. So, you need this class to get events from buttons and translate and call text or label to set the value. It’s a hand over job or intermediary object or controller.

Step 6: Select MyController. Click File - Write Class Files…. Accept to overwrite those classes.

Step 7: Close Interface Builder.Step

8: Fix implementation for MyController as shown below:

@implementation

MyController- (IBAction)random:(id)sender

{[label setIntValue:random()%100];}- (IBAction)seed:(id)sender {srandom(time(NULL));[label setStringValue:@"Seed Set"];}- (void)awakeFromNib {NSCalendarDate *date = [NSCalendarDate calendarDate];//[label setStringValue:[date description]];[label setObjectValue:date];}

@end

Note: awakeFromNib is the init() method called to set the text to something rather than “Label” on the screen when loaded.

Step 9: Build & Run. App will look like the following:

Download the project: RandomNumberGenerator.zip


Leave a Reply