Skip to content
Defining a Class
step 1/5

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 +)
  • @end closes the block
  • self is the receiver inside a method (like this)

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…