ios - 为什么调用 super 是此方法的最后一件事而不是第一件事?

标签 ios swift swift5 ipados

我边学边学 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/

相关文章:

ios - 在内部应用程序的情况下访问客户端 ios 应用程序崩溃报告

objective-c - 将新 pod 添加到现有项目时“无法发出预编译 header ”

ios - 检查 FaceID 是否正确?

swift - Alamofire 无法将 header 转换为 HTTPHeaders 来传递多部分 PUT 请求

iphone - Cocos2d - animationwithframes :delay: deprecated

ios - 为两个不同分支上的版本创建 Xcode 项目的 zip 存档

ios - mainBundle 上的 appStoreReceiptURL 总是返回 nil

json - Swift JSON 解码字典失败

swift - 我无法将图像放入 Swift 5 中的 UIButton

swift - 在 ARImageTrackingConfiguration 中同时跟踪两个对象