Objective-C Cheat Sheet
Fundamental Objective-C syntax covering classes, properties, messaging, ARC memory management, and protocols.
Hello World
A minimal Objective-C program.
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { NSString *greeting = @"Hello, World!"; NSLog(@"%@", greeting); } return 0;}
Interface & Implementation
Declaring a class with properties and methods.
// Person.h@interface Person : NSObject@property (nonatomic, strong) NSString *name;@property (nonatomic, assign) NSInteger age;- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;- (void)sayHello;@end// Person.m@implementation Person- (instancetype)initWithName:(NSString *)name age:(NSInteger)age { self = [super init]; if (self) { _name = name; _age = age; } return self;}- (void)sayHello { NSLog(@"Hi, I'm %@", self.name);}@end
Properties & Messaging
Core object and messaging syntax.
- [obj method]- Square-bracket message send syntax
- @property (nonatomic, strong)- Declares an object property, auto-synthesizes getter/setter
- self / super- Reference to the current instance / the superclass
- nil- Null object pointer; messaging nil is a safe no-op
- [[Person alloc] init]- Allocate memory, then initialize an instance
- id- Generic object pointer type, any Objective-C object
Memory Management (ARC)
Automatic Reference Counting basics.
- ARC- Automatic Reference Counting; the compiler inserts retain/release calls for you
- strong- Owns the referenced object, keeps it alive
- weak- Non-owning reference, automatically becomes nil when the object is deallocated
- retain/release- Managed automatically under ARC; do not call manually in ARC code
- @autoreleasepool- Block that drains autoreleased objects at its end
Protocols
Defining and conforming to a protocol.
@protocol Greetable <NSObject>- (void)greet;@optional- (void)farewell;@end@interface Robot : NSObject <Greetable>@end@implementation Robot- (void)greet { NSLog(@"Beep boop, hello!");}@end
Collections & Literals
Arrays, dictionaries, and modern literal syntax.
NSArray *arr = @[@"a", @"b", @"c"];NSString *first = arr[0];NSDictionary *dict = @{@"name": @"Ada", @"age": @36};NSNumber *age = dict[@"age"];NSMutableArray *m = [NSMutableArray arrayWithArray:arr];[m addObject:@"d"];[m removeObjectAtIndex:0];NSNumber *boxed = @(3 + 4); // boxed expression
Blocks
Closures for callbacks and enumeration.
int (^square)(int) = ^(int x) { return x * x; };int result = square(5); // 25NSArray *nums = @[@3, @1, @2];NSArray *sorted = [nums sortedArrayUsingComparator: ^NSComparisonResult(NSNumber *a, NSNumber *b) { return [a compare:b]; }];[nums enumerateObjectsUsingBlock:^(id obj, NSUInteger i, BOOL *stop) { NSLog(@"%lu: %@", (unsigned long)i, obj);}];
Categories & Extensions
Add methods to existing classes without subclassing.
// NSString+Reverse.h@interface NSString (Reverse)- (NSString *)reversedString;@end// NSString+Reverse.m@implementation NSString (Reverse)- (NSString *)reversedString { NSMutableString *r = [NSMutableString string]; for (NSInteger i = self.length - 1; i >= 0; i--) [r appendFormat:@"%C", [self characterAtIndex:i]]; return r;}@end
Foundation Types
Common Foundation framework classes.
- NSString- immutable Unicode text; NSMutableString is editable
- NSNumber- object wrapper for scalar numeric and boolean values
- NSData- immutable byte buffer for raw binary data
- NSDate- a single point in time; pair with NSDateFormatter
- NSError- domain, code, and userInfo for failure reporting
- NSNull- singleton placeholder for nil inside collections
Error Handling
The NSError by-reference pattern and exceptions.
NSError *error = nil;NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];if (!contents) { NSLog(@"Read failed: %@", error.localizedDescription);}@try { [array objectAtIndex:99];} @catch (NSException *ex) { NSLog(@"Caught: %@", ex.reason);} @finally { NSLog(@"cleanup");}
Prefer weak references for delegate properties (@property (nonatomic, weak) id<Delegate> delegate;) to avoid retain cycles between parent and child objects.