-
-
Save andrewsardone/5652968 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
// 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
#6 FTW