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.
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.
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.
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.
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.
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).
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
As you can see the "end"
print does happen before the Person
object is deallocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With