Memory Management & ARC
Objects live on the heap, and something has to decide when their memory can be freed. Objective-C uses reference counting: every object keeps a count of how many owners it has. When the count drops to zero, the object is deallocated immediately.
The idea
| Event | Effect on the count |
|---|---|
alloc, new, copy, mutableCopy create an object |
starts at 1 (you own it) |
| a new strong reference to the object (variable, property, collection) | +1 (retain) |
| a strong reference goes away or points elsewhere | −1 (release) |
| count reaches 0 | dealloc runs, memory is freed |
Before 2011 programmers wrote [obj retain] and [obj release] by hand ("manual retain-release", MRR). Today the compiler does it: ARC (Automatic Reference Counting) inserts the retains and releases for you at compile time. It is not a garbage collector: there's no background process, and objects die at predictable moments.
Watching dealloc
Overriding dealloc and logging in it lets you see when an object dies. Under ARC, dealloc is only for cleanup: never call [super dealloc], the compiler does it.
#import <Foundation/Foundation.h>
@interface Resource : NSObject
@property (nonatomic, copy) NSString *name;
- (instancetype)initWithName:(NSString *)name;
@end
@implementation Resource
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = [name copy];
NSLog(@"+ %@ created", _name);
}
return self;
}
- (void)dealloc {
NSLog(@"- %@ deallocated", _name);
}
@end
int main(void) {
@autoreleasepool {
Resource *a = [[Resource alloc] initWithName:@"A"];
Resource *b = [[Resource alloc] initWithName:@"B"];
NSLog(@"holding %@ and %@", a.name, b.name);
a = nil; // A's only owner is gone: freed right now
NSLog(@"after a = nil");
b = [[Resource alloc] initWithName:@"C"]; // reassigning releases B
NSLog(@"after reassigning, b is %@", b.name);
} // C is released when b goes out of scope
NSLog(@"program ends");
return 0;
}+ A created
+ B created
holding A and B
- A deallocated
after a = nil
+ C created
- B deallocated
after reassigning, b is C
- C deallocated
program ends
Each object was freed the moment its last strong reference disappeared, in a deterministic order.
Several owners
An object stays alive as long as any strong reference exists: local variables, properties and collections all count.
#import <Foundation/Foundation.h>
@interface Photo : NSObject
@property (nonatomic, copy) NSString *file;
@end
@implementation Photo
- (void)dealloc { NSLog(@"freed %@", _file); }
@end
@interface Album : NSObject
@property (nonatomic, strong) Photo *cover;
@end
@implementation Album
- (void)dealloc { NSLog(@"freed album"); }
@end
int main(void) {
@autoreleasepool {
Album *album = [Album new];
NSMutableArray *recent = [NSMutableArray array];
Photo *p = [Photo new];
p.file = @"beach.jpg";
album.cover = p; // owner 2
[recent addObject:p]; // owner 3
p = nil; // owner 1 gone, still alive
NSLog(@"local gone, cover is %@", album.cover.file);
album = nil; // album freed; its cover reference goes too
NSLog(@"album gone");
[recent removeAllObjects]; // the last owner: photo freed now
NSLog(@"recent cleared");
}
return 0;
}local gone, cover is beach.jpg
freed album
album gone
freed beach.jpg
recent cleared
Autorelease pools
Sometimes a method creates an object and returns it, without the caller "owning" it under the old naming rules ([NSString stringWithFormat:] for example). Such objects may be autoreleased: their release is postponed until the enclosing @autoreleasepool block ends. That's why every program wraps main in one.
Inside long loops that create lots of temporary objects, a nested pool keeps memory use low by freeing them every iteration:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSUInteger totalLength = 0;
for (int batch = 0; batch < 3; batch++) {
@autoreleasepool { // temporaries freed each batch
NSMutableArray *lines = [NSMutableArray array];
for (int i = 0; i < 1000; i++) {
[lines addObject:[NSString stringWithFormat:@"batch %d line %d", batch, i]];
}
totalLength += [[lines componentsJoinedByString:@"\n"] length];
}
}
NSLog(@"processed %lu characters", (unsigned long)totalLength);
}
return 0;
}processed 50667 characters
Note: In app code (iOS/macOS) the main run loop drains an autorelease pool for you after every event, so you only add pools yourself for big loops or background threads.
What ARC doesn't do
- C memory from
mallocstill needsfree, and Core Foundation objects (CFStringRef, …) still needCFRelease. - Retain cycles: two objects that strongly own each other never reach zero and leak. This is the main memory bug in ARC code; the next lesson shows how
weakfixes it.
| Under MRR (old code) | Under ARC |
|---|---|
[obj retain], [obj release], [obj autorelease] |
forbidden; the compiler inserts them |
[super dealloc] at the end of dealloc |
forbidden; automatic |
retainCount |
unavailable (and was never reliable) |
@property (retain) |
@property (strong) |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] |
@autoreleasepool { } |
Test yourself
When is an object deallocated under ARC?
- When the garbage collector runs
- When its last strong reference disappears
- At the end of main
- When you call dealloc
Under ARC, what must dealloc NOT do?
- Log a message
- Remove notification observers
- Call [super dealloc]
- Release C memory with free()
Why put an @autoreleasepool inside a long loop?
- To make the loop faster to compile
- To free autoreleased temporaries every iteration
- Because ARC requires it
- To prevent retain cycles