Last active
October 22, 2015 20:06
-
-
Save casspangell/285faff47e7d09914831 to your computer and use it in GitHub Desktop.
Weak Self in Blocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation XYZBlockKeeper | |
- (void)configureBlock { | |
self.block = ^{ | |
[self doSomething]; // capturing a strong reference to self | |
// creates a strong reference cycle | |
}; | |
} | |
... | |
@end | |
/* | |
It’s best practice to capture a weak reference to self, like this: | |
*/ | |
- (void)configureBlock { | |
XYZBlockKeeper * __weak weakSelf = self; | |
self.block = ^{ | |
[weakSelf doSomething]; // capture the weak reference | |
// to avoid the reference cycle | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment