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

news/2024/7/20 12:30:56 标签: 内存管理, python, 移动开发

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里面做这样的工作。

转载于:https://www.cnblogs.com/mglttkx/p/4846841.html


http://www.niftyadmin.cn/n/1078227.html

相关文章

骁龙660_骁龙675有资格成为“神U”骁龙660的继任者吗?

原标题:骁龙675有资格成为“神U”骁龙660的继任者吗?文/黑猫评测手机圈中,有三颗芯片已成“神话”--其一,是联发科P25,因被魅族打磨了整整一年成名;其二,是骁龙625,因省电够用被尊为…

oracle32 plsql,32位plsql developer连接64位oracle

正常情况下在64位的windows操作系统上安装完32位plsql developer后,是无法显示登陆窗口信息的(主要是database选项),下面提供一种方法解决1、下载plsql developer安装包及instantclient-basic-win32-10.2.0.52、windows上安装oracle client软件3、将下载的instantcl…

mybatis oracle悲观锁,mybatis plus 乐观锁插件

主要适用场景意图:当要更新一条记录的时候,希望这条记录没有被别人更新乐观锁实现方式:取出记录时,获取当前version更新时,带上这个version执行更新时, set version newVersion where version oldVersion…

stopped状态的进程 top 命令_Linux系统top命令详解:持续监听进程运行状态

ps命令可以一次性给出当前系统中进程状态,但使用此方式得到的信息缺乏时效性,并且,如果管理员需要实时监控进程运行情况,就必须不停地执行ps命令,这显然是缺乏效率的。为此,linux提供了top命令。top命令可以…

委托的一个实例

public class DelegateTest { // 声明delegate对象 public delegate void CompareDelegate(int a, int b); // 欲传递的方法,它与CompareDelegate具有相同的参数和返回值类型 public static void Compare(int a, int b) { Console.WriteLine((a > b).ToString(…

中班区域活动设计思路_【案例研究】幼教装备 | 幼儿科技活动的摇篮——金山区漕泾幼儿园科技操作室...

创建背景金山区漕泾幼儿园始创于1951年,是上海市一级幼儿园。本园自1997年开展幼儿科技教育研究至今,一直致力于科技操作室的开发与实践研究。科技操作室是幼儿科技活动教育资源物化形态中的一种,它对幼儿创新意识的培养作用深远。在科技操作…

matlab 由tag得到句柄,matlab做法

[教程] GUI指导教程系列(1):GUI入门基本操作为什么在MA TLAB中要使用GUI呢?其实GUI就是Matlab中的Visual Basic,是面向对象的编程,可以使Matlab程序的终端用户,即使不懂的Matlab也可以轻易操作该程序!如果没…

[转]OBOUT ASP.NET HTML Editor - Insert HTML

本文转自&#xff1a;http://www.obout.com/editor_new/sample_InsertHTML.aspx Example demonstrates how to access HTML Editors content at current selection/caret position from "outside" component. Example code <script type"text/JavaScript&quo…