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.