gpt4 book ai didi

ios - Swift:在从初始化器返回之前,没有在所有路径上调用 'super.init'?

转载 作者:可可西里 更新时间:2023-11-01 01:08:00 24 4
gpt4 key购买 nike

我在我的类中的 init 的最后一个大括号中收到此错误。该类类似于以下内容(我在发生错误的地方销售):

class RecordingViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

let cameraButton:UIButton?
let camPreview:UIView?

init (cameraButton: UIButton!, camPreview: UIView!) {
self.cameraButton = cameraButton
self.camPreview = camPreview

} //get error here

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

//do a bunch of other stuff
}

我看过herehere寻求解决方案,但两者似乎都不是非常糟糕的解决方案,就是对那个问题过于具体,因此它们对我不起作用。

我希望以一种可以帮助我理解为什么会发生此错误的方式解决我的问题。

最佳答案

由于您继承自 UIViewController,因此您应该在 init 函数中设置变量后立即调用 super.init

当您继承一个类并实现一个新的初始化函数或覆盖它自己的初始化函数时,您应该(几乎)总是调用 super.init。举个例子吧,你继承自 UIViewController。 UIViewController 有一些初始化函数,你可以用它们来初始化 View Controller 。如果您不调用 super.init,这些函数中的所有代码都不会被调用,并且 View Controller 可能不会被初始化。

无论如何,这段代码应该适合你:

class ViewController: UIViewController {

var button: UIButton?

init(button: UIButton) {
self.button = button
super.init(nibName: nil, bundle: nil)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

关于ios - Swift:在从初始化器返回之前,没有在所有路径上调用 'super.init'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com