我有UINavigationController
和UITableViewController
的子類。UINavigationController子類的便捷初始化使子類常量初始化兩次
要初始化子類,我決定使用一些調用超類的指定初始化方法的一些convenience init
方法。此外,每個子類有一些let
常數:
let someValue: SomeClass = SomeClass()
每個類都成功地通過調用其新創建convenience init
方法初始化。
問題是let
常量被初始化TWICE在UINavigationController
子類中。
import UIKit
import PlaygroundSupport
final class Navigation: UINavigationController {
convenience init(anyObject: Any) {
self.init(rootViewController: UIViewController())
}
let service = Constant("Constant Initialization -> Navigation")
}
final class Table: UITableViewController {
convenience init(anyObject: Any) {
self.init(style: .plain)
}
let service = Constant("Constant Initialization -> Table")
}
class Constant: NSObject {
init(_ string: String) {
super.init()
debugPrint(string)
}
}
Navigation(anyObject: NSNull())
Table(anyObject: NSNull())
我們是否允許使用上述的convenience init
?爲什麼?
爲什麼convenience init
行爲在這兩種情況下有所不同?
經過與:版本8.2β(8C30a),版本8.2(8C38),版8.2.1(8C1002)
P.S.以上代碼的遊樂場日誌:
"Constant Initialization -> Navigation"
"Constant Initialization -> Navigation"
"Constant Initialization -> Table"
謝謝你的回答。而且我仍然不明白爲什麼這兩種情況下的便利初始行爲是不同的? – iWheelBuy
因此,'convenience'初始化使用上面的Objective-C示例init模式,其中有兩個init調用('[super init]'和'[self.class alloc] init ...]'。理解,會直接進入''[self.class alloc] init ...]'初始化程序路徑,因此不會雙重初始化,這就是導致您看到的問題的原因。 – BHendricks
我認爲在這兩種情況下我打電話給指定的初始值,不是嗎? – iWheelBuy