Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does swift handle nil values in memory

Tags:

ios

swift

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.

like image 487
David Biga Avatar asked Jun 10 '16 16:06

David Biga


People also ask

Is nil a value in Swift?

In Swift: nil is not a pointer, it's the absence of a value of a certain type. NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed.

How does memory allocation work in Swift?

In Swift, memory management is handled by Automatic Reference Counting (ARC). Whenever you create a new instance of a class ARC allocates a chunk of memory to store information about the type of instance and values of stored properties of that instance.

How is memory management done in Swift?

Swift uses Automatic Reference Counting (ARC) to track and manage your app's memory usage. In most cases, this means that memory management “just works” in Swift, and you don't need to think about memory management yourself.

What does nil mean in Swift?

In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language.


1 Answers

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.

like image 153
Luca Angeletti Avatar answered Oct 20 '22 22:10

Luca Angeletti