[英]Swift use of unimplemented initializer 'init()'
Part 1 第1部分
I am writing a Today Widget extension using NSExtensionPrincipalClass
instead of storyboard. 我正在使用
NSExtensionPrincipalClass
而不是storyboard编写Today Widget扩展。 I implemented the following required init 我实现了以下必需的init
required init(coder aDecoder: NSCoder) {
tableView = UITableView()
cellIdentifier = "kCellIdentifier"
super.init(coder: aDecoder)
}
However, when I run the project I get the following error 但是,当我运行该项目时,我收到以下错误
use of unimplemented initializer 'init()'
So, by putting this additional code in the project, it will fix the problem but it doesn't seem right to initialize variables in multiple places 因此,通过在项目中添加此附加代码,它将解决问题,但在多个位置初始化变量似乎不正确
override init() {
tableView = UITableView()
cellIdentifier = "kCellIdentifier"
super.init()
}
Part 2 第2部分
So I answered part 1 of my question below but I still don't know why the following solution wouldn't work? 所以我回答了下面问题的第一部分,但我仍然不知道为什么以下解决方案不起作用?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
cellIdentifier = "kCell"
tableView = UITableView()
super.init(nibName: nil, bundle: nil)
}
As per Swift's documentation 根据Swift的文档
“If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.”
“如果您的子类提供了所有超类指定初始化器的实现 - 通过按照规则1继承它们,或者通过提供自定义实现作为其定义的一部分 - 那么它会自动继承所有超类便捷初始化器。”
In UIViewController, init(nibName:bundle:)
is the only designated initialized so why am I not automatically inherits init()
and init(coder:)
? 在UIViewController中,
init(nibName:bundle:)
是唯一指定的初始化,为什么我不自动继承init()
和init(coder:)
?
So here is the solution to the first part of my question after re-read swift's initializer chapter and look at UIViewController header file 所以这里是重新阅读swift的初始化器章节并查看UIViewController头文件后我的问题的第一部分的解决方案
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init() {
cellIdentifier = "kCellIdentifier"
tableView = UITableView()
super.init(nibName: nil, bundle: nil)
}
One of the key to this solution is init(nibName:bundle:)
which is a designated initializer which you must call whether you use storyboard or not. 这个解决方案的关键之一是
init(nibName:bundle:)
,它是一个指定的初始化程序,无论你是否使用故事板,都必须调用它。
Keys take away: 钥匙带走:
convenience init
will call init(nibName:bundle:)
for you using nil
as arguments. convenience init
将使用nil
作为参数为您调用init(nibName:bundle:)
。 So if you are not inherited the default init() method then it is your responsibility to override it and call init(nibName:bundle:)
init(nibName:bundle:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.