<分区>
当从另一个类创建子类时,需要覆盖
init()
函数,但不能覆盖deinit
'功能'。
这在 Swift 中可能吗?
这是一个例子
class Foo {
init(){
print("Foo created")
}
deinit {
print("Foo gone")
}
}
class Bar: Foo {
override init(){
print("Bar created")
}
//Is not overwritten here
deinit {
print("Bar gone")
}
}
内部示例 View Controller
override func viewDidLoad() {
super.viewDidLoad()
var f: Foo?
f = Foo()
f = Bar()
f = nil
}
输出
Foo created //Foo object initialised - Foo init() called
Foo created //Foo init() called before calling Bar init()? no call to superclass though..
Bar created //Bar object initialised - Bar init() called
Foo gone //Foo deinit called as Foo instance replaced by Bar instance
Bar gone //Bar deinit called as Bar instance holds no references and is destroyed
Foo gone //Foo deinit called again as part of Bar object destruction?
添加到我关于扩展 deinit
的原始问题中:
在示例代码中,覆盖 init()
似乎会导致调用父类(super class)的 init()
函数。这就是正在发生的事情吗?
当 Bar
实例被取消初始化时会发生相同的行为。这也是这里发生的事情吗?