
这是我的实现示例,简化为尽可能简单,可以在游乐场中运行.
import UIKitpublic class MyNavigationController: UINavigationController { public var anyVar: Int? public init(anyVar: Int) { let vIEwController = UIVIEwController() super.init(rootVIEwController: vIEwController) self.anyVar = anyVar } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }}let navigationController = MyNavigationController(anyVar: 42) 最后一行是崩溃,有一个EXC_BAD_INSTRUCTION.当我在Xcode中运行时,它在运行时告诉我init(nibname nibnameOrNil:String?,bundle nibBundleOrNil:NSBundle?)丢失了.
如果我覆盖该方法:
public overrIDe init(nibname nibnameOrNil: String?,bundle nibBundleOrNil: NSBundle?) { super.init(nibname: nibnameOrNil,bundle: nibBundleOrNil)} ……一切运作良好:您可以尝试自己的游乐场.
我不明白为什么.这对我来说听起来不合逻辑.
UIVIEwController文档说:
If you subclass UIVIEwController,you must call the super implementation of this
method,even if you aren’t using a NIB. (As a convenIEnce,the default init method will do this for you,
and specify nil for both of this methods arguments.)
但我的init(nibname nibnameOrNil:String?,bundle nibBundleOrNil:NSBundle?)覆盖从super.init(rootVIEwController:vIEwController)初始化调用!
如果没有覆盖它,我想应该调用UIVIEwController的init(nibname:bundle :),但不是.
我仍然无法理解为什么覆盖该方法并调用super使程序更好地工作. IMO,覆盖一个方法,而只调用super.thisMethod是完全没用的,它只在调用堆栈中添加一个方法调用.
我必须遗漏一些关于Swift init方法的要点,但我无法弄清楚是什么.
解决方法 这是因为Swift继承初始化器的方式.如果未在当前类中声明任何初始值设定项,则编译器将从父类继承所有初始值设定项.但是如果你覆盖/添加新的初始化器(并且你用init(anyVar :)做),Swift将不会自动从父类继承初始化器,因此无法从子类访问它们,这会导致运行时崩溃.如果您对超出此行为的原因感兴趣,可以查看Intermediate Swift部分和2014年WWDC(约34分钟标记,他们正在谈论初始化器继承)
总结以上是内存溢出为你收集整理的Swift UINavigationController子类中的强制init覆盖全部内容,希望文章能够帮你解决Swift UINavigationController子类中的强制init覆盖所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)