Skip to content

Instantly share code, notes, and snippets.

@erikprice
Forked from bencochran/gist:5647603
Created May 28, 2013 16:58
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 erikprice/5664273 to your computer and use it in GitHub Desktop.
Save erikprice/5664273 to your computer and use it in GitHub Desktop.
// 1.
// “Safe” but retain cycle.
[self setCompletionBlock:^{
NSLog(@"1: %@", self->_foo);
}];
// 2.
// Unsafe. Could dereference nil.
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
NSLog(@"2: %@", weakSelf->_foo);
}];
// 3.
// Unsafe. Could be nilled out on another thread between check and dereference.
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
if (weakSelf)
NSLog(@"3: %@", weakSelf->_foo);
}];
// 4.
// Unsafe. Could dereference nil.
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
__strong BCThing *strongSelf = weakSelf;
NSLog(@"4: %@", strongSelf->_foo);
}];
// 5.
// Safe
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
__strong BCThing *strongSelf = weakSelf;
if (strongSelf)
NSLog(@"5: %@", strongSelf->_foo);
}];
// 6.
// Safe and clean
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
NSLog(@"5: %@", [weakSelf foo]);
}];
// ... or, if you need to check for nil
__weak BCThing *weakSelf = self;
[self setCompletionBlock:^{
__strong BCThing *strongSelf = weakSelf;
if (strongSelf)
[someArray addObject:strongSelf];
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment