欢迎查看block连载博客:
【block编程第一篇】block语法
【block编程第二篇】block捕获变量和对象;
【block编程第三篇】block的内存管理。
【block编程第四篇】block内部实现;
【block编程第五篇】block中如何避免循环引用(当前)
------------------------------------------------------------------------------------------------------------------------------
@interface KSViewController () { id _observer; } @end @implementation KSViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. KSTester * tester = [[KSTester alloc] init]; [tester run]; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"TestNotificationKey" object:nil queue:nil usingBlock:^(NSNotification *n) { NSLog(@"%@", self); }]; } - (void)dealloc { if (_observer) { [[NSNotificationCenter defaultCenter] removeObserver:_observer]; } }
The block is copied by the notification center and (the copy) held until the observer registration is removed.
因此,通知中心会拷贝 block 并持有该拷贝直到解除 _observer 的注册。在 ARC 中,在被拷贝的 block 中无论是直接引用 self 还是通过引用 self 的成员变量间接引用 self,该 block 都会 retain self。
这两个问题,可以用 weak–strong dance 技术来解决。该技术在 WWDC 中介绍过:2011 WWDC Session #322 (Objective-C Advancements in Depth)
__weak KSViewController * wself = self; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"TestNotificationKey" object:nil queue:nil usingBlock:^(NSNotification *n) { KSViewController * sself = wself; if (sself) { NSLog(@"%@", sself); } else { NSLog(@"<self> dealloc before we could run this code."); } }];下面来分析为什么该手法能够起作用。