Skip to content

Instantly share code, notes, and snippets.

@vendruscolo
Created November 11, 2014 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendruscolo/ac4bf2f3e8705ed998dc to your computer and use it in GitHub Desktop.
Save vendruscolo/ac4bf2f3e8705ed998dc to your computer and use it in GitHub Desktop.
- (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
}
}];
}
@gscalzo
Copy link

gscalzo commented Nov 11, 2014

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment