Step 1 of 5 · Reading · ~1 min
Learn
Classes and Methods
An Objective-C class needs an interface (header) and implementation:
#import <Foundation/Foundation.h>
@interface Point : NSObject
{
int _x;
int _y;
}
@property int x;
@property int y;
- (double)distanceFrom:(Point *)other;
@end
@implementation Point
@synthesize x = _x, y = _y;
- (double)distanceFrom:(Point *)other {
int dx = self.x - other.x;
int dy = self.y - other.y;
return sqrt(dx * dx + dy * dy);
}
@end
@interface ClassName : Superclass-- declares the class@property-- declares that the class exposes a getter/setter for a value- (returnType)methodName...-- instance method (the-)+ (returnType)methodName...-- class method (the+)@endcloses the blockselfis the receiver inside a method (likethis)
Important -- explicit synthesis. Modern Apple Clang auto-generates a backing ivar and accessor
methods for every @property, so you can skip @synthesize entirely. This judge runs on the
GNUstep runtime, which does not auto-synthesize. If you only write @property int x; and then
use self.x, the code compiles fine but crashes at runtime with something like
does not recognize selector setX:.
Always declare an explicit backing ivar and synthesize it yourself:
@interface Point : NSObject
{
int _x; // backing ivar
}
@property int x;
@end
@implementation Point
@synthesize x = _x; // wires self.x / self.x = ... to _x
@end
Creating instances:
Point *p = [[Point alloc] init];
p.x = 3;
p.y = 4;
The [Class alloc] allocates memory; init initializes. Modern code may use [Class new] which
combines them. Wrap your main body in @autoreleasepool { ... } when working with Objective-C
objects.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…