I want to know when static
variable will be released, so i create like below:
class A {
init() {
print("A init")
}
deinit {
print("A deinit")
}
}
class B {
static let a = A()
deinit {
print("B deinit")
}
init() {
print("B init")
}
}
var b: B? = B()
B.a
b = nil
When variable a
's deinit
was called? If b = nil
then A
's deinit
wasn't called.
Objects will only be deinitialized when nothing else is holding a strong reference to it.
In your case, b
is not holding a reference to a
. The class B
is.
Setting b
to nil does not do anything to a
because b
never ever held a reference to a
. b
is essentially irrelevant. a
and b
are non-related objects.
Now that we know the class B
is holding a reference to a
, can we somehow destroy the class B
so that a
can be deinitialised? The answer is no. a
is like a variable in the global scope. a
will only be deinitialised when the program stops.
Another way to make something get deinitialised is by setting all the references to it to refer to something else. But since in this case a
is declared with let
, you can't really change it.
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