我們用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];
}];
}