This is what I have learned: when using self
retained block
- I need a
weakSelf
to break retain cycle - I need a
strongSelf
to preventself
from becoming nil half-way
so I want to test if a strongSelf
can really keep self
alive like so:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewDidLoad");
self.test = @"test";
NSLog(@"%@",self.test);
__weak typeof(self)weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
__strong typeof(weakSelf)strongSelf = weakSelf;
strongSelf.test = @"newTest";
NSLog(@"%@",strongSelf.test);
});
}
- (void)dealloc {
NSLog(@"dealloc");
}
@end
The ViewController will be pushed into a navigationController and pop out immediately. The output is
why the null?
There is another question I have a project which contains tons of weakSelf
without strongSelf
in the block and I get plenty of signal 11 crash. Is it related? Is it worth to add strongSelf
to each of them?