美文网首页ios开发问题记录iOS
ARC下NSException可能会内存泄露

ARC下NSException可能会内存泄露

作者: _Thinking_ | 来源:发表于2016-03-19 01:31 被阅读188次

在使用Instrumnents对程序进行内存测试的时候,发现有几处异常处理的地方提示内存泄露。经过分析得知,因为异常处理,改变代码执行路径,导致编译生成的 release 代码没有执行

简单写了些测试代码验证:

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    @try {
        NSMutableArray *stringList = [[NSMutableArray alloc] init];
        for (int i = 0; i < 100; i++) {
            [stringList addObject: @"string instance."];
        }
        [self throwException];
    }
    @catch (NSException *exception) {
        NSLog(@"catch Exception : %@", exception);
    }
    @finally {
        
    }
}

- (void)throwException
{
    [NSException raise:@"An Exception." format:@"Exception Description."];
}

反复进出这个页面几次后,在Instruments上果然看到提示内存泄露,而且泄露的地方就指明是 @try{ } 里面创建的对象。

memory-leak

解决思路

1, 尽量不要在@try{}里面有操作,导致对象的引用引用计数增加。@try{ } 语句块里面只有有可能抛出异常的语句。

修改后的代码:

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSMutableArray *stringList = [[NSMutableArray alloc] init];
    for (int i = 0; i < 100; i++) {
        [stringList addObject: @"string instance."];
    }
    
    @try {
        [self throwException];
    }
    @catch (NSException *exception) {
        NSLog(@"catch Exception : %@", exception);
    }
    @finally {
        
    }
}

最后用Instruments检查一下,一切正常了。

2, 查看了苹果的开发文档,发现有这么一段描述:

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.
A program may be compiled with the option -fobjc-arc-exceptions in order to enable these, or with the option -fno-objc-arc-exceptions to explicitly disable them, with the last such argument “winning”.

相关文章

  • ARC下NSException可能会内存泄露

    在使用Instrumnents对程序进行内存测试的时候,发现有几处异常处理的地方提示内存泄露。经过分析得知,因为异...

  • 内存泄漏/管理

    ARC 下内存泄露的那些点performSelector延时调用导致的内存泄露iOS ARC下几种导致内存泄露的场...

  • 使用富文本OHAttributedLabel

    使用教程: 请在arc下使用,不要arc与mrc混用造成内存泄露! 源码地址 http://pan.baidu....

  • ARC下内存泄露总结

    1、Block的循环引用   在iOS4.2时,Apple推出ARC内存管理机制。这是一种编译期的内存管理方式,在...

  • ARC 下内存泄露的那些点

    ARC 下内存泄露的那些点 一、block 系列 在 ARC 下,当 block 获取到外部变量时,由于编译器无法...

  • 内存及性能优化

    1. 用ARC管理内存 ARC除了帮你避免内存泄露,ARC还可以帮你提高性能,它能保证释放掉不再需要的对象的内存。...

  • iOS 内存管理机制

    最近接手的一个 APP 项目有内存泄露问题, 由于用了 ARC 管理内存, 使得找出哪里内存泄露了变得更加困难, ...

  • 增强iOS应用程序性能方法

    1. 使用ARC进行内存管理 ARC除了能避免内存泄露外,还有助于程序性能的提升 2.在适当的情况下使用reuse...

  • iOS自问自答:总结内存管理与优化

    目录 ARC下如何避免内存泄露?如何检测? 你是如何做内存优化的? __block你知道多少?在什么时候使用? 你...

  • iOS性能优化:Instruments使用实战

    这里讲述在没有ARC的情况下,如何使用Instruments来查找程序中的内存泄露,以及NSZombieEnabl...

网友评论

    本文标题:ARC下NSException可能会内存泄露

    本文链接:https://www.haomeiwen.com/subject/sudhlttx.html