Skip to the workspace
Pebellslearn by building
Choosing a Language  ›  Lesson

Objective-C Basics

Objective-C Basics 12 minObjective-C is C with objects added, where you call a method by sending a message to a receiver inside square brackets.

ios / Objective-C Basics

Explore each scene at your own pace.

01 · The rule

The rule

Objective-C Basics

Before you write a line of Swift, you will meet Objective-C: in older TrailLog-style codebases, in Stack Overflow answers from 2012, and in the names of Apple's own types. NSString, NSDate, UIViewController — those prefixes come from Objective-C. You do not need to write it daily, but you do need to read it without panic.

The rule

Objective-C is C plus messages sent in square brackets.

Objective-C is a strict superset of C: any valid C code is valid Objective-C. On top of C it adds objects, and the way you talk to an object is by sending it a message inside square brackets.

// Hike.h — the interface: what a Hike offers
@interface Hike : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) double distanceKm;
- (NSString *)summary;
@end

// Hike.m — the implementation: how it does it
@implementation Hike
- (NSString *)summary {
    return [NSString stringWithFormat:@"%@: %.1f km", self.name, self.distanceKm];
}
@end

Read it piece by piece:

  • Two files per class. The .h header declares the public interface; the .m file holds the code. Other files #import the header.
  • @ marks Objective-C additions to C: @interface, @property, @end, and string literals like @"Ridge Loop" (a plain "..." would be a C string).
  • * on object types. Every object is reached through a pointer: NSString *name.
  • - and +. A minus starts an instance method, a plus starts a class method.
  • Messages. [hike summary] sends the summary message to hike. With arguments, the method name is split into labelled parts: [hike setName:@"Ridge Loop"].

One surprising rule: sending a message to nil is allowed and simply returns nil or zero. Nothing crashes, which hides bugs — one of the reasons Swift was designed differently.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.