1

In MRC in iOS, when an object is set to nil,

myObject = nil; 

It's told that memory leak will happen, as the myObject will not point to a memory address. The memory which it was pointing before will be lost. So we need to release the myObject and then only we can set nil. Can someone help me understanding, what will happen if we set nil to myObject in ARC? If we have something like this

myObject = SomeObject(value:10);
SomeObject myObject_another = myObject;
myObject = nil;
  1. Will ARC call [myObject release] when we set myObject = nil?
  2. Will this lead to a memory leak?
  3. Will it call [myObject_another release]as well when we set myObject = nil?

Please help me understand the difference between ARC and non-ARC.

sandpat
  • 1,478
  • 12
  • 30
rishu1992
  • 1,414
  • 3
  • 14
  • 33
  • 1
    ARC manages the release cycle automatically, it does not call release method when you set `myObject = nil`. This does not call memory leak. You do not have required set all objects as nil. Whenever the class removes from the stack ARC releases all the allocated memory of that class. – Kampai Jan 27 '20 at 05:38

1 Answers1

2

You can think that compiler inserts retains / releases every time when new reference created / destroyed(or reassigned). So it will look like:

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. Yes. Release called: ref count decreased. Memory is NOT deallocated.
  2. No memory leak here.
  3. No. Object is still alive and can be accessed via myObject_another.

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

Denis
  • 89
  • 4
  • If ref count is 1 assigning nil would instantly dealloc and release memory. Otherwise you're correct and the final round of checks and deallocation (if needed) is performed at the end of the runloop. – Kamil.S Jan 27 '20 at 10:03