我边学边学 Swift。
我发现像这样的函数 viewDidLoad()
和许多其他函数有时是这样写的:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
有时这样写:
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
}
我的意思是调用 super.viewDidLoad()
作为函数内部的第一件事还是最后一件事?
它对程序本身有什么不同?
最佳答案
首先,docs不要说你需要调用 super
。将其与例如viewWillAppear(_:)
,其 docs状态:
If you override this method, you must call
super
at some point in your implementation.
因此,仅当您有 UIViewController
的自定义子类时才需要调用 super
,我们称它为 BaseViewController
,它在 viewDidLoad()
。
当您从 BaseViewController
继承时,您可能需要调用 super
来完成 BaseViewController
的工作。根据它的性质,您需要在子类的 viewDidLoad()
的开头、中间某处或末尾执行此操作。这取决于此 BaseViewController
以正确记录它。
这是一个人为的例子:
class ColorfulViewController: UIViewController {
/// Defines background color of view. Override in subclass.
var shinyColor: UIColor = .red
/// Sets the background color. Make sure to call `super` in subclass.
func viewDidLoad() {
backgroundColor = shinyColor
}
}
class PinkViewController: ColorfulViewController {
override var shinyColor: UIColor = .systemPink
func viewDidLoad() {
super.viewDidLoad() // This one doesn't matter where it goes.
// Additional work.
}
}
另一个人为的例子,你想在最后调用 super
:
class CountingViewController: UIViewController {
var count: Int = 0
/// Counts the subviews. When subclassing, make sure to call `super` *after*
/// view is fully configured.
func viewDidLoad() {
count = view.subviews.count
}
}
class FooViewController: CountingViewController {
override var shinyColor: UIColor = .systemPink
func viewDidLoad() {
// Additional work.
super.viewDidLoad()
}
}
关于ios - 为什么调用 super 是此方法的最后一件事而不是第一件事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59447532/