I am currently following the Apple Documentation. Here is my question:
class Person {
let name: String
init(name: String) {
self.name = name
println("\(name) is being initialized")
}
deinit {
println("\(name) is being deinitialized")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var reference1: Person?
var reference2: Person?
var reference3: Person?
reference1 = Person(name: "John Appleseed")
// prints "John Appleseed is being initialized
reference2 = reference1
reference3 = reference1
reference1 = nil
reference2 = nil
}
}
After reference1
equals nil
, ARC deallocates the instance and prints "John Appleseed is being deinitialized"
Should not it be deallocates after reference3 = nil
?
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.
Both GC (Garbage Collection) and ARC aim to take burden from the developer so that they need not worry about the reference count, when they should free objects, etc. GC is used in programming languages like Java, C#, Go and other scripting languages and ARC is used in Objective-C and Swift languages.
An essential concept in ARC is the retain count, which is a number that keeps track of how many objects are “holding onto” to another object. ARC only applies to reference types such as classes, and not to value types like structs. Value types are copied, so they don't work with references.
Automatic Reference counting or ARC, is a form of garbage collection in which objects are deallocated once there are no more references to them, i.e. no other variable refers to the object in particular.
The problem here is a matter of scope. We can find out more with breakpoints.
Here, we are stopped just before we initialize reference1
.
All variables are expectedly nil
:
And after the initialization of reference1
?
Okay, let's skip forward to after reference2
and reference3
are set:
All three variables point to the same memory location, and we can see the initializer only ran once. These all point to the same location.
Let's step forward:
reference1
is now pointing to None
. It is nil
. The deinit
mmethod has not been called and printed its message.
Let's step forward some more:
Now reference1
and reference2
are both expectedly nil
. The println
statements I've added were called. But deinit
did not run and reference3
is not nil
.
The next step is stepping all the way out of the method. Once we're out of the method, the variables are out of scope and the deinit
is called:
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