簡體   English   中英

UIViewController 的默認初始化在哪里?

[英]Where is the default init for UIViewController?

所以我最近遇到了這個問題,我編寫的一些 Swift 5 代碼在 Xcode 11.0 但不是 11.2.1 中編譯,后者抱怨我的類沒有默認初始化程序擴展 UIViewController(它定義沒有初始化程序)當我嘗試實例化它。

事實上,當我查看 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.
*/

我找到了一種解決方法來完成這項工作,我只需要定義調用超類初始化器的所有三個初始化器,默認工作如評論中所述,但我仍然感到困惑我是如何逃脫使用當我在任何地方都找不到它時,一直使用默認初始值設定項。 注釋中描述的默認初始值設定項實際定義在哪里?

通常當你定義一個變量而不初始化它時會發生這種情況。 所以如果你的代碼中有這樣的變量 -

var name:string

改變它像

var name:string = "" 

或者

var name = string()

你找不到init()聲明,因為它是一個方便的初始化程序。

當您嘗試覆蓋它時,Xcode 會給您以下錯誤:

初始化程序不會覆蓋其超類中的指定初始化程序

和這條消息:

  1. 嘗試在此處覆蓋便利初始值設定項(UIKit.UIViewController)

並且您不能覆蓋 Swift 中的便利初始化程序,並且便利初始化程序必須調用 self.init 之一而不是超類之一。

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

您可以調用 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?]?) {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM