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;
@end
*** CounterController.m ***
#import "CounterController.h"
@implementation CounterController
- (IBAction)minus_button_pushed:(id)sender {
count--;
[display_update setIntValue:count];
}
- (IBAction)p10_button_pushed:(id)sender {
count+=10;
[display_update setIntValue:count];
}
- (IBAction)plus_button_pushed:(id)sender {
count++;
[display_update setIntValue:count];
}
@end
Things of note:
- Obj-C uses
import
instead ofinclude
. - The class
CounterController
is a subclass ofNSObject
. - Inside the brackets are the instance variables
display_update
andcount
. - The
IBOutlet
beforedisplay_update
means thedisplay_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 toIBAction 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 todisplay_update.setIntValue(count).
http://www.gmonline.demon.co.uk/cscene/CS7/CS7-05.html
http://en.wikipedia.org/wiki/Objective-C
http://www.otierney.net/objective-c.html
No comments:
Post a Comment