使用未实现的初始化程序

使用未实现的初始化程序

本文介绍了致命错误:对类使用未实现的初始化程序 'init(coder:)'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定用 Swift 继续我剩下的项目.当我将自定义类(UIViewcontroller 的子类)添加到我的故事板视图控制器并加载项目时,应用程序突然崩溃并出现以下错误:

I decided to continue my remaining project with Swift. When I add the custom class (subclass of UIViewcontroller) to my storyboard view controller and load the project, the app crashes suddenly with the following error:

致命错误:使用未实现的初始化程序 'init(coder:)' 用于类

这是一个代码:

import UIKit

class TestViewController: UIViewController {

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // Custom initialization
    }

    override func viewDidLoad() {
        super.viewDidLoad()
              // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // #pragma mark - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
}

请提出建议

推荐答案

Issue

这是由于目标 UIViewController 上没有初始化器 init?(coder aDecoder: NSCoder) 造成的.该方法是必需的,因为从 UIStoryboard 实例化一个 UIViewController 会调用它.

Issue

This is caused by the absence of the initializer init?(coder aDecoder: NSCoder) on the target UIViewController. That method is required because instantiating a UIViewController from a UIStoryboard calls it.

要了解我们如何从 UIStoryboard 初始化 UIViewController,请查看 这里

To see how we initialize a UIViewController from a UIStoryboard, please take a look here

因为 Objective-C 会自动继承所有必需的 UIViewController 初始值设定项.

Because Objective-C automatically inherits all the required UIViewController initializers.

Swift 出于安全考虑,默认情况下不继承初始化程序.但是如果所有属性都有值(或可选)并且子类没有定义任何指定的初始化器,它将继承超类的所有初始化器.

Swift by default does not inherit the initializers due to safety. But it will inherit all the initializers from the superclass if all the properties have a value (or optional) and the subclass has not defined any designated initializers.

在目标UIViewController

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}


2.第二种方法

删除目标 UIViewController 上的 init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) 将从超类继承所有必需的初始值设定项为 Dave Wood 指出他在下面的答案


2. Second method

Removing init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) on your target UIViewController will inherit all of the required initializers from the superclass as Dave Wood pointed on his answer below

这篇关于致命错误:对类使用未实现的初始化程序 'init(coder:)'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:00