【问题标题】:Where is the default init for UIViewController?UIViewController 的默认初始化在哪里?
【发布时间】:2020-04-02 14:17:16
【问题描述】:

所以我最近遇到了这个问题,我编写的一些 Swift 5 代码在 Xcode 11.0 但不是 11.2.1 中编译,后者抱怨我的扩展 UIViewController 的类没有默认初始化程序(它定义了 no初始化程序)当我尝试实例化它时。

确实,当我查看 UIViewController 的定义时,只有以下两个定义:

public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
public init?(coder: NSCoder)

它还包含一条注释,似乎暗示也应该存在一个默认初始化程序,但我找不到它。

/*
  The designated initializer. 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.) In the specified NIB, the File's Owner proxy should
  have its class set to your view controller subclass, with the view outlet connected to the main view. If you
  invoke this method with a nil nib name, then this class' -loadView method will attempt to load a NIB whose
  name is the same as your view controller's class. If no such NIB in fact exists then you must either call
  -setView: before -view is invoked, or override the -loadView method to set up your views programatically.
*/

我找到了一种解决方法来完成这项工作,我只需要定义调用超类初始化程序的所有三个初始化程序,默认工作如评论中所述,但我仍然困惑我是如何逃脱的当我在任何地方都找不到它时,一直使用默认初始化程序。注释中描述的默认初始化器实际定义在哪里?

【问题讨论】:

  • 显示您的代码。

标签: ios swift


【解决方案1】:

通常,当您定义一个变量但没有对其进行初始化时,就会发生这种情况。因此,如果您的代码中有这样的变量-

var name:string

改成这样

var name:string = "" 

var name = string()

【讨论】:

  • 我非常有信心这不是原因;我的班级没有成员。另外,如果您的初始化程序使其中一个成员未初始化,这不是错误吗?如果是问题所在,我认为我的解决方法不会解决此问题。
【解决方案2】:

你找不到init() decladation,因为它是一个方便的初始化器。

当你试图覆盖它时,Xcode 会给你这个错误:

Initializer 不会覆盖父类中指定的初始化器

还有这条信息:

  1. 尝试在此处覆盖便捷初始化程序 (UIKit.UIViewController)

而且你不能在 Swift 中重写便捷初始化器,并且便捷初始化器必须调用 self.init 之一而不是超类之一。

convenience init() {
    self.init(nibName: nil, bundle: nil)
}

【讨论】:

  • 我不想覆盖它,我想调用它。
【解决方案3】:

您可以调用 init() 作为默认构造函数。

import UIKit

class InstantWebViewController: UIViewController {

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

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

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    init(_ object: [String: Any?]?) {
    }
}

【讨论】:

  • 前三个初始化程序基本上正是我为解决这个问题所做的。不过,我试图了解 UIViewController 的默认初始化程序实际上来自哪里。
猜你喜欢
  • 1970-01-01
  • 2011-06-18
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多