iOS之报错上架填坑iOS开发实用技术看装B

不易察觉的NSException内存泄露

2017-04-22  本文已影响107人  kamous

前两天在Instrument扫到了一处内存泄露,和常见的Block、NSTimer、Target-Action之类循环引用无关,泄漏的call tree指向了一个属性的set的位置,在ARC下这种提示还真奇怪。



非常费解,在Demo里简单还原下事故现场:

@interface ExceptionViewController : BaseViewController
@property (nonatomic, strong) DataModel *dataModel;//包含name属性的简单Model
@end

@implementation ExceptionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadDataModel];
}

- (void)dealloc {
    [self unloadDataModel];
    NSLog(@"Dealloc VC:%@", self);
}

- (void)loadDataModel {
    [self setDataModel:[DataModel new]];
    [self.dataModel addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)unloadDataModel {
    @try {
        [self.dataModel removeObserver:self forKeyPath:@"name"];
    } @catch (NSException *exception) {
        NSLog(@"Exception:%@",exception);
    }
}
@end

Leaks-Leaks by Backtrace内可以看到泄露的是DataModel对象,这页说明上图定位的set代码行正确指出了泄露的对象。
在unloadDataModel内尝试做如下修改,泄露竟然就消失了:

- (void)unloadDataModel {
    @try {
        [self.dataModel removeObserver:self forKeyPath:@"name"];
    } @catch (NSException *exception) {
        NSLog(@"Exception:%@",exception);
    } @finally {
        [self setDataModel:nil];
    }
}

然而unloadDataModel里为什么有个try-catch?因为有可能抛出NSException异常,那为什么简单的KVO removeObserver:forKeyPath:会抛出异常?
打断点在unloadDataModel里跟了一下,发现在这个ViewController生命周期里,unloadDataModel执行了两次,第二次执行必定抛出异常:

Cannot remove an observer <ExceptionViewController 0x7f8b17d1e8b0> for the key path "name" from <DataModel 0x7f8b17f1d380> because it is not registered as an observer

好吧,可能就是NSException的锅。搜索一番,发现了这个:

By default in Objective C, ARC is not exception-safe for normal releases:

  • It does not end the lifetime of __strong variables when their scopes are abnormally terminated by an exception.
  • It does not perform releases which would occur at the end of a full-expression if that full-expression throws an exception.

ARC下发生了异常,对象的没有正常走出其作用域,ARC没能自动添加上release,不保证正常释放对象的。在上面这种情况,self指代的ExceptionViewController能正常dealloc,而self.dataModel就不能释放。
另外注意第一条描述的情况,像这样下面这样在@try{}里声明使用的局部变量,也是有泄露隐患的:



正确的姿势应该是:

- (void)test {
    DataModel *dataModel = [DataModel new];
    NSLog(@"Empty Model:%@", dataModel);
    @try {
        //某些抛出异常的代码
        @throw [NSException exceptionWithName:@"Exc" reason:@"Test" userInfo:nil];
    } @catch (NSException *exception) {
        NSLog(@"Exception:%@",exception);
    }
}

对了,回到上文,为什么unloadDataModel乌龙地调用了两次?因为ExceptionViewController的基类BaseViewController的dealloc中,也调用了unloadDataModel:

@implementation BaseViewController
- (void)dealloc {
    [self unloadDataModel];
}
@end

所以这个问题最准确的改法不是在@finally中[self setDataModel:nil],而是修改逻辑保证unloadDataModel只调用一次。

另外,如果一个类中不得不使用NSException,逻辑又不能梳理清保证尽可能不抛出异常,那还有一个避免内存泄露的方法,在项目的Target-Build Phases中,双击该类文件,添加-fobjc-arc-exceptions描述符,当然不建议采用该方法,因为编译器为了保证此处发生NSException还能正常释放内存添加了需要不必要的保护代码,降低性能。其讨论参考Why does “try catch” in Objective-C cause memory leak?

总结:
避免NSException产生内存泄露,需要注意:

参考文章:
《Objective-C, ARC and Exceptions》
《Why does “try catch” in Objective-C cause memory leak?》

上一篇下一篇

猜你喜欢

热点阅读