iOS:将对象设置为nil时,ARC和MRC有什么区别?

问题描述 投票:1回答:1

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

myObject = nil; 

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

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

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

ios objective-c swift automatic-ref-counting manual-retain-release
1个回答
2
投票

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

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访问。

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

© www.soinside.com 2019 - 2024. All rights reserved.