Created
November 11, 2014 14:22
-
-
Save vendruscolo/ac4bf2f3e8705ed998dc to your computer and use it in GitHub Desktop.
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
- (void)doStuff { | |
// Using a weak ref, we allow self to be deallocated before | |
// the block gets called. If in the block we used `self` | |
// directly, we'd create a retain cycle. | |
__weak typeof(self) weakSelf = self; | |
[self doSomethingElseWithBlock:^{ | |
// Now keep a strong reference to self. This will fail | |
// if `self` got deallocated before the block got | |
// called. This is needed to ensure that self (if | |
// alive) doesn't get deallocated between uses, because | |
// `weakSelf` is a `__weak` ref. This, however, isn't | |
// needed if in the block you use `self` only once. | |
__strong typeof(self) strongSelf = weakSelf; | |
if (strongSelf) { | |
// do things with self, as it's guaranted to be | |
// still alive. | |
// Check the "Repeatedly using a __weak reference" | |
// compiler warning to catch these errors | |
} | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yep, my question was more philosophical and regarding the design of the compiler (14chars aren't enough :-))
using your code (which is a good practice), my question is: there is any reason to use a weak reference to self inside a block? :-)
The compiler could had this code without the programmer needs to do it...
"The problem isn’t the code, therefore; it’s the fact that the code is necessary."
http://intersections.tumblr.com/post/85684818284/irrelevance