Skip to content

Instantly share code, notes, and snippets.

@bencochran
Last active March 5, 2023 21:55
Show Gist options
  • Save bencochran/5647603 to your computer and use it in GitHub Desktop.
Save bencochran/5647603 to your computer and use it in GitHub Desktop.
Block, threads, ivars, ARC, yay!
// 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