【问题标题】:iOS: What is the difference in ARC and MRC when an object is set to nil?iOS:当对象设置为 nil 时,ARC 和 MRC 有什么区别?
【发布时间】:2020-05-12 12:00:00
【问题描述】:

在iOS的MRC中,当一个对象设置为nil时,

myObject = nil; 

被告知会发生内存泄漏,因为 myObject 不会指向内存地址。它之前指向的记忆将会丢失。所以我们需要释放myObject,然后我们才能设置nil。 有人可以帮助我理解,如果我们在 ARC 中将 nil 设置为 myObject 会发生什么? 如果我们有这样的事情

myObject = SomeObject(value:10);
SomeObject myObject_another = myObject;
myObject = nil;
  1. 当我们设置myObject = nil时,ARC会调用[myObject release]吗?
  2. 这会导致内存泄漏吗?
  3. 当我们设置myObject = nil时,它也会调用[myObject_another release]吗?

请帮助我了解 ARC 和非 ARC 之间的区别。

【问题讨论】:

  • ARC自动管理发布周期,设置myObject = nil时不会调用发布方法。这不叫内存泄漏。您不需要将所有对象都设置为 nil。每当类从堆栈中删除时,ARC 就会释放该类的所有分配内存。

标签: ios objective-c swift automatic-ref-counting manual-retain-release


【解决方案1】:

您可以认为每次创建/销毁(或重新分配)新引用时,编译器都会插入保留/释放。所以它看起来像:

myObject = SomeObject(value:10); /// Memory allocated and ref count increased. 
SomeObject myObject_another = myObject; /// ref count increased (now 2). 
myObject = nil; /// Reassigning -> ref count decreased. SomeObject still alive.
...
/// When myObject_another is destroyed or reassigned ref count will be decreased. It's 0 now -> memory deallocated. 
  1. 是的。发布调用:引用计数减少。内存未释放。
  2. 这里没有内存泄漏。
  3. 没有。对象还活着,可以通过 myObject_another 访问。

苹果文章: https://developer.apple.com/library/archive/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226

【讨论】:

  • 如果 ref count 为 1,分配 nil 将立即释放内存。否则你是正确的,最后一轮检查和释放(如果需要)在运行循环结束时执行。
猜你喜欢
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多