zoukankan      html  css  js  c++  java
  • 深度:ARC会导致的内存泄露

    iOS提供了ARC功能,很大程度上简化了内存管理的代码。

    但使用ARC并不代表了不会发生内存泄露,使用不当照样会发生内存泄露。

    下面列举两种内存泄露的情况。

    1,循环参照

    A有个属性参照B,B有个属性参照A,如果都是strong参照的话,两个对象都无法释放。

    这种问题常发生于把delegate声明为strong属性了。

    例,

    @interface SampleViewController

    @property (nonatomic, strong) SampleClass *sampleClass;

    @end

    @interface SampleClass

    @property (nonatomic, strong) SampleViewController *delegate;

    @end

    上例中,解决办法是把SampleClass 的delegate属性的strong改为assing即可。

    2,死循环

    如果某个ViewController中有无限循环,也会导致即使ViewController对应的view关掉了,ViewController也不能被释放。

    这种问题常发生于animation处理。

    例,

    比如,

    CATransition *transition = [CATransition animation];

    transition.duration = 0.5;

    tansition.repeatCount = HUGE_VALL;

    [self.view.layer addAnimation:transition forKey:"myAnimation"];

    上例中,animation重复次数设成HUGE_VALL,一个很大的数值,基本上等于无限循环了。

    解决办法是,在ViewController关掉的时候,停止这个animation。

    -(void)viewWillDisappear:(BOOL)animated {

        [self.view.layer removeAllAnimations];

    }

    内存泄露的情况当然不止以上两种。

    即使用了ARC,我们也要深刻理解iOS的内存管理机制,这样才能有效避免内存泄露。

  • 相关阅读:
    python 四舍五入
    Elasticsearch 入门
    Mac下ElasticSearch安装、Kibana
    Mysql 终端中文显示乱码
    Zookeeper 在 Kafka 中的作用
    mac 安装Kafka
    Creating a NuGet Package in 7 easy steps
    Updating and Publishing a NuGet Package
    ASP.NET Core 发布
    An entry point cannot be marked with the 'async' modifier
  • 原文地址:https://www.cnblogs.com/lovewx/p/4023850.html
Copyright © 2011-2022 走看看