iOS夯实:ARC时代的内存管理

文章转自 ARC时代的内存管理

什么是ARC

Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. Rather than having to think about retain and release operations [^1]

[^1]: Transitioning to ARC Release Notes

ARC提供是一个编译器的特性,帮助我们在编译的时候自动插入管理引用计数的代码。
最重要的是我们要认识到ARC的本质仍然是通过引用计数来管理内存。因此有时候如果我们操作不当,仍然会有内存泄露的危险。下面就总结一下ARC时代可能出现内存泄露的场景。

内存泄露类型

  1. 循环引用

    基于引用计数的内存管理机制无法绕过的一个问题便是循环引用(retain cycle)
    (Python同样也采用了基于引用计数的内存管理,但是它采用了另外的机制来清除引用循环导致的内存泄露,而OC和Swift需要我们自己来处理这样的问题[^2])

    • 对象之间的循环引用:使用弱引用避免
    • block与对象之间的循环引用:

    会导致Block与对象之间的循环引用的情况有:

    self.myBlock = ^{ self.someProperty = XXX; };  

    对于这种Block与Self直接循环引用的情况,编译器会给出提示。

    但是对于有多个对象参与的情况,编译器便无能为力了,因此涉及到block内使用到self的情况,我们需要非常谨慎。(推荐涉及到self的情况,如果自己不是非常清楚对象引用关系,统一使用解决方法处理)

    someObject.someBlock = ^{ self.someProperty = XXX; }; //还没有循环引用
    self.someObjectWithABlock = someObject; // 导致循环引用,且编译器不会提醒

    解决方案:

    __weak SomeObjectClass *weakSelf = self;
    
    SomeBlockType someBlock = ^{
    SomeObjectClass *strongSelf = weakSelf;
    if (strongSelf == nil) {
    // The original self doesn't exist anymore.
    // Ignore, notify or otherwise handle this case.
    }
    [strongSelf someMethod];
    };

    我们还有一种更简便的方法来进行处理,实际原理与上面是一样的,但简化后的指令更易用。

    @weakify(self)
    [self.context performBlock:^{
    // Analog to strongSelf in previous code snippet.
    @strongify(self) // You can just reference self as you normally would. Hurray.
    NSError *error;
    [self.context save:&error]; // Do something
    }];

    你可以在这里找到@weakify,@strongify工具:MyTools_iOS

[^2]: How does Python deal with retain cycles?

    1. NSTimer

      一般情况下在action/target模式里 target一般都是被weak引用,除了NSTimer。

      + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds
      target:(id)target
      selector:(SEL)aSelector
      userInfo:(id)userInfo
      repeats:(BOOL)repeats

      在官方文档中:

      target
      The object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to this object until it (the timer) is invalidated.

      Timer Programming Topics :

      A timer maintains a strong reference to its target. This means that as long as a timer remains valid, its target will not be deallocated. As a corollary, this means that it does not make sense for a timer’s target to try to invalidate the timer in its dealloc method—the dealloc method will not be invoked as long as the timer is valid.

      举一个例子,一个Timer的Target是ViewController.

      这个时候,如果我们是在dealloc方法里让timer invalidate,就会造成内存泄露.

      事实上,timer是永远不会被invalidate.因为此时VC的引用计数永远不会为零。因为Timer强引用了VC。而因为VC的引用计数不为零,dealloc永远也不会被执行,所以Timer永远持有了VC.

      因此我们需要注意在什么地方invalidate计时器,我们可以在viewWillDisappear里面做这样的工作。

iOS夯实:ARC时代的内存管理的更多相关文章

  1. 【转】iOS夯实:ARC时代的内存管理

    iOS夯实:ARC时代的内存管理 什么是ARC Automatic Reference Counting (ARC) is a compiler feature that provides autom ...

  2. ARC时代的内存管理

    什么是ARC Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory manag ...

  3. iOS经典面试题总结--内存管理

    iOS经典面试题总结--内存管理 内存管理 1.什么是ARC? ARC是automatic reference counting自动引用计数,在程序编译时自动加入retain/release.在对象被 ...

  4. ARC下的内存管理

    1.ARC下单对象内存管理 局部变量释放对象随之被释放 int main(int argc, const char * argv[]) { @autoreleasepool { Person *p = ...

  5. iOS学习17之OC内存管理

    1.内存管理的方式 1> iOS应用程序出现Crash(闪退),90%的原因是因为内存问题. 2> 内存问题 野指针异常:访问没有所有权的内存,如果想要安全的访问,必须确保空间还在 内存泄 ...

  6. iOS学习之Object-C语言内存管理

    一.内存管理的方式      1.iOS应用程序出现Crash(闪退),90%的原因是因为内存问题.      2.内存问题:      1)野指针异常:访问没有所有权的内存,如果想要安全的访问,必须 ...

  7. objective-c启用ARC时的内存管理 (循环引用)

    PDF版下载:http://download.csdn.net/detail/cuibo1123/7443125          在Objective-C中,内存的引用计数一直是一个让人比较头疼的问 ...

  8. iOS之Block总结以及内存管理

    block定义 struct Block_descriptor { unsigned long int reserved; unsigned long int size; void (*copy)(v ...

  9. objective-c启用ARC时的内存管理

    PDF版下载:http://download.csdn.net/detail/cuibo1123/7443125      在objective-c中,内存的引用计数一直是一个让人比較头疼的问题.尤其 ...

随机推荐

  1. nyoj 199 无线网络覆盖

    无线网络覆盖 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 我们的乐乐同学对于网络可算得上是情有独钟,他有一个计划,那就是用无线网覆盖郑州大学. 现在学校给了他一个 ...

  2. 在CentOS 6.2上安装 MemcacheQ 最新版

    1.      安装 yum install gcc cc make libevent libevent-devel 2.      安装Berkeley DB 下载:http://www.oracl ...

  3. Oracle- 表查询

    这些都比较基础,还是重温一下. 一.简单的查询语句1.查询表结构sql>desc dept; (使用PL/SQL Developer查询时,必需在命令窗口才能使用该语句) 2.查询所有列sql& ...

  4. Modernizr 与 Polyfill

    之前提到,Modernizr 是 HTML5 和 CSS3 的特性检测工具,这里简单介绍一下它的用法.最简单的用法是在页面的 <head> 中添加 Modernizr 的 JavaScri ...

  5. Postgresql:prepared statement "S_1" already exists

    近期由于业务需要和一些json的存储查询需要,把新的应用切到pgsql上来,刚刚切好,是可以正常使用的,但是偶尔会来一下 java连接pgsql 偶尔出现 这个错.   org.postgresql. ...

  6. The Sorrows of Young Werther

    The Sorrows of Young Werther J.W. von Goethe Thomas Carlyle and R.D. Boylan Edited by Nathen Haskell ...

  7. SVN的版本日期

    SVN还可以使用版本日期来指定某个版本,日期格式使用ISO-8601标准,一般是yyyy-mm-dd hh:mm:ss.当你指定一个日期,SVN会在版本库中找到最接近这个日期的版本. SVN对日期的解 ...

  8. Android获唯一标识

    Android开发中有时候因业务需要客户端要产生一个唯一的标识符使服务器能识别某台Android设备,目前一般使用三种标识符分别为 DeviceId . AndroidId . MAC地址 . 获取D ...

  9. Android 如何修改默认的searchable items。

    前言          欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处:          CSDN:http://www.csdn.net        ...

  10. 应用之星推出“图文app”制作工具,并附上教程

    应用之星已推出的"图文"app制作工具,是高速制作图文电子书,图文杂志等一切有关图文资料的app生成工具,以下跟大家介绍"图文"制作教程,简单快捷,大致分三大步 ...