Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift when static variable was released

Tags:

swift

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.

like image 529
William Hu Avatar asked Dec 08 '22 17:12

William Hu


1 Answers

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.

like image 114
Sweeper Avatar answered Dec 27 '22 10:12

Sweeper