Strong, Weak & Retain Cycles
ARC frees an object when nothing holds a strong reference to it. If two objects hold strong references to each other, neither count ever reaches zero, and both leak even when the rest of the program has forgotten them. This is a retain cycle (or reference cycle).
A cycle in action
#import <Foundation/Foundation.h>
@class Owner;
@interface Pet : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Owner *owner; // strong back-reference: a mistake
@end
@interface Owner : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Pet *pet;
@end
@implementation Pet
- (void)dealloc { NSLog(@"Pet %@ freed", _name); }
@end
@implementation Owner
- (void)dealloc { NSLog(@"Owner %@ freed", _name); }
@end
int main(void) {
@autoreleasepool {
Owner *sam = [Owner new];
sam.name = @"Sam";
Pet *rex = [Pet new];
rex.name = @"Rex";
sam.pet = rex;
rex.owner = sam; // the cycle: Sam -> Rex -> Sam
sam = nil;
rex = nil;
NSLog(@"variables cleared, but nothing was freed");
}
NSLog(@"end of program");
return 0;
}variables cleared, but nothing was freed
end of program
No "freed" message appears: both objects are unreachable but still alive. In a real app, every screen you open and close this way would leak memory.
@class Owner; is a forward declaration: it tells the compiler that a class named Owner exists before its interface appears.
Breaking the cycle with weak
The fix is to decide who owns whom. An owner owns its pet; the pet merely refers to its owner, so that reference should be weak:
#import <Foundation/Foundation.h>
@class Owner;
@interface Pet : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, weak) Owner *owner; // weak: doesn't keep the owner alive
@end
@interface Owner : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Pet *pet;
@end
@implementation Pet
- (void)dealloc { NSLog(@"Pet %@ freed", _name); }
@end
@implementation Owner
- (void)dealloc { NSLog(@"Owner %@ freed", _name); }
@end
int main(void) {
@autoreleasepool {
Owner *sam = [Owner new];
sam.name = @"Sam";
Pet *rex = [Pet new];
rex.name = @"Rex";
sam.pet = rex;
rex.owner = sam;
NSLog(@"%@'s owner is %@", rex.name, rex.owner.name);
sam = nil; // Sam's last strong reference: Sam is freed
NSLog(@"after sam = nil, rex.owner is %@", rex.owner ? @"set" : @"nil");
rex = nil;
}
NSLog(@"end of program");
return 0;
}Rex's owner is Sam
Owner Sam freed
after sam = nil, rex.owner is nil
Pet Rex freed
end of program
Two things happened: Sam was freed as soon as the local variable let go, and Rex's owner property became nil automatically. Weak references are "zeroing": they never point at freed memory.
The rules of thumb
| Relationship | Reference |
|---|---|
| parent → child (owner → pet, view controller → its views, array → its items) | strong |
| child → parent (pet → owner, cell → table) | weak |
| delegate (table view → its delegate) | weak |
a block property that uses self |
capture self weakly (next lessons) |
Weak local variables
__weak works on local variables too. Combined with nested scopes you can watch a weak reference turn into nil:
#import <Foundation/Foundation.h>
@interface Session : NSObject
@property (nonatomic, copy) NSString *user;
@end
@implementation Session
- (void)dealloc { NSLog(@"session for %@ ended", _user); }
@end
int main(void) {
@autoreleasepool {
__weak Session *observer;
{
Session *session = [Session new];
session.user = @"nora";
observer = session;
NSLog(@"observing %@", observer.user);
} // session's strong variable ends here
NSLog(@"observer is now %@", observer ? @"alive" : @"nil");
// Common mistake: assigning a new object straight to a weak variable
__weak Session *lost = [Session new]; // nobody holds it strongly
NSLog(@"lost is %@", lost ? @"alive" : @"nil");
}
return 0;
}main.m:22:25: warning: assigning retained object to weak variable; object will be released after assignment [-Warc-unsafe-retained-assign]
__weak Session *lost = [Session new]; // nobody holds it strongly
^ ~~~~~~~~~~~~~
1 warning generated.
observing nora
session for nora ended
observer is now nil
session for (null) ended
lost is nil
The last case is a classic bug: a brand-new object stored only in a weak variable is released immediately. Clang warns about it (the warning is printed above the program's output), and the unnamed session's dealloc runs without a user name, which prints as (null).
unsafe_unretained and assign
Two older qualifiers also don't retain, but they don't zero either: after the object dies they point at freed memory, and using them crashes or corrupts data.
| Qualifier | Retains? | Becomes nil? |
|---|---|---|
strong / __strong |
yes | — |
weak / __weak |
no | yes |
unsafe_unretained / __unsafe_unretained |
no | no: dangling pointer |
assign (on an object property) |
no | no |
Tip: Use
weakfor non-owning object references.assignis for C values likeNSIntegerandBOOL; on object pointers it's a bug waiting to happen.
Test yourself
What is a retain cycle?
- A loop that retains objects
- Two or more objects holding strong references to each other so none is freed
- An object released twice
- A weak reference to nil
In a parent/child relationship, which reference should usually be weak?
- Parent to child
- Child to parent
- Both
- Neither
What happens to __weak id w = [NSObject new];?
- w keeps the object alive
- The object is freed immediately and w is nil
- Compile error
- The object leaks