IOS 在MRC(非ARC)内存管理方式下,中如果Block调用了self的方法,那self的引用计数会被block +1, 如果处理不当会当值内存泄漏。
@implementation ISSChartLineViewController
- (void)dealloc
{
[_lineView release];
[_changeDataButton release];
[super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
_lineView = [[ISSChartLineView alloc] initWithFrame:self.view.bounds lineData:[[ISSChartDataGenerator sharedInstance] lineData]];
_lineView.didSelectedLines = ^ISSChartHintView *(ISSChartLineView *lineView, NSArray *lines, NSInteger index, ISSChartAxisItem *xAxisItem) {
return [self getHintView:lineView lines:lines index:index xAxisItem:xAxisItem];
};
//here need to optimization
[self.view addSubview:_lineView];
[self.view bringSubviewToFront:self.changeDataButton];
}
如果这样写,回退到上一个界面的时候dealloc方式是不会调用的,因为self被block应用在,这样会导致self一直放在内存中,修改如下即可:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
_lineView = [[ISSChartLineView alloc] initWithFrame:self.view.bounds lineData:[[ISSChartDataGenerator sharedInstance] lineData]];
__block typeof(self)weakSelf = self;
_lineView.didSelectedLines = ^ISSChartHintView *(ISSChartLineView *lineView, NSArray *lines, NSInteger index, ISSChartAxisItem *xAxisItem) {
return [weakSelf getHintView:lineView lines:lines index:index xAxisItem:xAxisItem];
};
//here need to optimization
[self.view addSubview:_lineView];
[self.view bringSubviewToFront:self.changeDataButton];
}