【ios】 block里引用成员变量导致memory leak
bolck语句不允许修改成员变量,如果需要修改成员变量需要在修饰成员变量前加__block
block的循环引用就是一个天坑,一不小心就绕进去了,在block里引用成员变量,会引起memory leak,原代码如下
@interface KEUserInfoParentSettingView() { CGFloat progressWidth; }
-(UIView *) ivSelectProgress { if (!_ivSelectProgress) { _ivSelectProgress = [[UIView alloc] init]; __weak typeof(self) weakSelf = self; _ivSelectProgress.themeChangeCallBack = ^{ progressWidth = weakSelf.ivSelectProgress.width; [weakSelf updateView]; }; } return _ivSelectProgress; }
这种情况下,应该将成员变量改为属性,并使用weakself处理,代码如下
@property (nonatomic, assign) CGFloat progressWidth;
-(UIView *) ivSelectProgress { if (!_ivSelectProgress) { _ivSelectProgress = [[UIView alloc] init]; __weak typeof(self) weakSelf = self; _ivSelectProgress.themeChangeCallBack = ^{ weakSelf.progressWidth = weakSelf.ivSelectProgress.width; [weakSelf updateView]; }; } return _ivSelectProgress; }