内存泄露(iOS)

2018-04-26  本文已影响17人  怪客半

之前一直都没有花费精力来关注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方法中

上一篇 下一篇

猜你喜欢

热点阅读