Tuesday, 21 October 2008

Objective-C Classes

Objective-C (Obj-C) is C with Object Oriented Programming tacked on. The object syntax takes some time to get used to, as it is decidedly different from the normal C++/Java syntax.

There are two parts for an object in Obj-C, which are the interface and the implementation. The parts should be stored separately, the interface in a header file (*.h) and the implementation is a *.m file.

The interface stores the instance variables and the prototypes for the class and instance methods. The implementation defines those methods.

Sample code:

*** CounterController.h ***
#import < Cocoa/Cocoa.h >
@interface CounterController : NSObject {
IBOutlet id display_update;
int count;
- (IBAction)minus_button_pushed:(id)sender;
- (IBAction)p10_button_pushed:(id)sender;
- (IBAction)plus_button_pushed:(id)sender;

*** CounterController.m ***
#import "CounterController.h"
@implementation CounterController
- (IBAction)minus_button_pushed:(id)sender {
[display_update setIntValue:count];
- (IBAction)p10_button_pushed:(id)sender {
[display_update setIntValue:count];
- (IBAction)plus_button_pushed:(id)sender {
[display_update setIntValue:count];

Things of note:
  • Obj-C uses import instead of include.
  • The class CounterController is a subclass of NSObject.
  • Inside the brackets are the instance variables display_update and count.
  • The IBOutlet before display_update means the display_update is an output on the GUI display in the Interface Builder.
  • id is a general type, meaning any object.
  • (IBAction)minus_button_pushed:(id)sender translates to IBAction minus_button_pushed(id sender).
  • The - before the methods classify them as instance methods, + for class methods.
  • The brackets [] indicate messaging, [display_update setIntValue:count] translates to display_update.setIntValue(count).


No comments: