David Biga David Biga - 1 year ago 98
Swift Question

How does swift handle nil values in memory

I know that ARC uses reference counting with compiler inserted increment and decrement operations when (strong) references are being set. It clears out the memory after the object's last reference group goes out of scope.

My question contains around having a var:

var key = NSData?

This by default is nil if no value present. Now after I assign it and than reassign the value to nil -
key = NSData()
. Will this remove that data from memory that was previously there?

Any helpful articles would be appreciated.

Answer Source

When you write

var key = NSData?

The key variable is created into the Stack and a nil value is assigned to it.

Let's say next you assign an object to key so

key = NSData()

Now an object of type NSData is created into the Heap. And the address of that object is written into the key variable (into the Stack). ARC also takes note that now the refereneCount of the NSData object is 1 because it is referenced by 1 variable.

Now we assign again nil to key

key = nil

then ARC detects that the NSData living into the Heap is no longer referenced. So its referenceCount drops to 0 and ARC removes it from memory (or probably marks that region of the Heap as free memory that can be used again).

When exactly is the object deallocated?

As @AaronBrager pointed out, the object is not instantly deallocated from memory. It is actually deallocated when the autorelease pool is drained.

The following example does show it

enter image description here

As you can see the "end" print does happen before the Person object is deallocated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download