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];
}
@endRead it piece by piece:
- Two files per class. The
.hheader declares the public interface; the.mfile holds the code. Other files#importthe 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 thesummarymessage tohike. 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.
The shortcut
To read any Objective-C line, find the brackets, then read receiver first, message second. Nested brackets are evaluated inside out, just like nested function calls.
The line
NSString *text = [[hike summary] uppercaseString];
A common misreading is to treat the first word inside the brackets as the method. It is always the receiver; the method comes after it.
Drills
Answer fast — trust the rule.
In [trail addHike:newHike], which part is the receiver?
Which file normally declares a class's public properties and methods?
What happens when you send a message to nil in Objective-C?
Which line is an Objective-C string object literal?
Remember
- Objective-C is C plus objects, and you talk to objects by sending messages in square brackets.
- Read brackets inside out: receiver first, then message;
.hdeclares,.mimplements. - Trap: messaging
nilsilently returns nil or zero instead of failing loudly.
