Reading — step 1 of 5
Learn
~1 min readClasses and Methods
An Objective-C class needs an interface (header) and implementation:
#import <Foundation/Foundation.h>
@interface Point : NSObject
@property int x;
@property int y;
- (double)distanceFrom:(Point *)other;
@end
@implementation Point
- (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— auto-synthesizes getter/setter- (returnType)methodName...— instance method (the-)+ (returnType)methodName...— class method (the+)@endcloses the blockselfis the receiver inside a method (likethis)
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.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…