我们用block 的时候,由于内存没有释放,导致循环引用,其实很简单,只有我们用_weak 就解决了 贴代码了
#import "DetailViewController.h" @interface DetailViewController () @end @implementation DetailViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserverForName:@"key" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { [self notification]; }]; } - (void)notification { NSLog(@"%@", NSStringFromSelector(_cmd)); } - (void)dealloc { NSLog(@"%@", NSStringFromSelector(_cmd)); } @end
当DetailViewController返回上个VC时,发现DetailViewController没有执行dealloc方法释放内存,这就形成了内存泄露。主要由于NSNotificationCenter的block一直持有self,形成了强引用。
2 ARC模式解决循环引用
ARC模式下使用__weak解决循环引用。
- (void)viewDidLoad { [super viewDidLoad]; __weak DetailViewController *wSelf = self; [[NSNotificationCenter defaultCenter] addObserverForName:@"key" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { [wSelf notification]; }]; }2 ReactiveCocoa解决循环引用。
我们可以使用第三方库ReactiveCocoa解决循环引用。
当然第三种方法,你需要导入#import "RACEXTScope.h" - (void)viewDidLoad { [super viewDidLoad]; @weakify(self); [[NSNotificationCenter defaultCenter] addObserverForName:@"key" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { @strongify(self); [self notification]; }]; }ReactiveCocoa