内存泄露(iOS)

之前一直都没有花费精力来关注App的内存泄露问题,最近知道了MLeaksFinder这个第三方库。第一次导入就报错了,找到泄露的地方之前还很懵,找到之后真的是哭笑不得,涉及的是很常见的知识点。

2018.4.26

1.在self持有的block中直接使用self导致的内存泄露
错误代码:

[[self.showAlertButton2 rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tradition" message:@"RAC方法触发" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"action1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"Tradition action1.");
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action1];
        [alert addAction:action2];
        [self presentViewController:alert animated:YES completion:nil];
    }];

正确代码:

__weak typeof(self) weakSelf = self;
[[self.showAlertButton2 rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tradition" message:@"RAC方法触发" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"action1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"Tradition action1.");
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action1];
        [alert addAction:action2];
        // 不使用weakSelf而直接使用self的话会发生内存泄露
        [weakSelf presentViewController:alert animated:YES completion:nil];
    }];

代码地址 -> viewDidLoad方法中

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容