block内强引用导致的内存泄露

2017-07-11  本文已影响0人  Masazumi柒

最近在项目中添加了MLeaksFinder,用于排查内存泄露的地方。
平常weakself的意识很强,因为引用self的频率较高,遇到block内的self,基本都会意识到用weakself,但这次有一个控制器的内存泄露一直找不到原因。代码如下

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    PPROfflinemapHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    PPROfflinemapProvinceModel *model = _sectionData[section];
    view.model = model;
    //更变了section的cell数量,所以要刷新
    view.block = ^(BOOL isExpanded){
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];//此处其实强引用了tableview,导致tableview循环引用无法释放
    };
    return view;
}

正确的代码如下

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    PPROfflinemapHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    PPROfflinemapProvinceModel *model = _sectionData[section];
    view.model = model;
    //更变了section的cell数量,所以要刷新
    __weak typeof(UITableView *)weaktableview = tableView;
    view.block = ^(BOOL isExpanded){
        [weaktableview reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    };
    return view;
}

使用block时应该多注意循环引用的问题,不仅仅是self,其他实例变量也应该注意。

上一篇下一篇

猜你喜欢

热点阅读