Quick use of the unimplemented 'init ()' initializer

Part 1

I am writing a Today Widget extension with help NSExtensionPrincipalClass

instead of storyboard. I have executed the following required 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 adding this extra code to 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

So, I answered part 1 of my question below, but I still don't know why the following solution won't work?

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    cellIdentifier = "kCell"
    tableView = UITableView()
    super.init(nibName: nil, bundle: nil)
}

      

According to Swift documentation

"If your subclass provides an implementation of its entire superclass with designated initializers - either by inheriting them according to rule 1, or by providing a custom implementation as part of its definition - then it automatically inherits all the conveniences of the superclass Initializers."

The UIViewController init(nibName:bundle:)

is the only one assigned initialized, so why don't I automatically inherit init()

and init(coder:)

?

+3


source to share


1 answer


So here is the solution to the first part of my question after the re-read chapter of the quick initializer and take a look at the UIViewController header file

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 keys to this solution is init(nibName:bundle:)

which is the designated initializer that you should call if you are using a storyboard or not.



Keys taken away:

  • If you do not specify the value of your variables when you declare them, you will lose all inheritance of the initializers from your superclass. This means that you have to provide your own init or override the superclass initializers and call the appropriate designated initializer for your superclass. In addition, you must implement any required initializers.
  • By default, in UIViewController, it convenience init

    will be called init(nibName:bundle:)

    to be used nil

    as arguments. Therefore, if you do not inherit the default init () method, you are responsible for canceling it and callinginit(nibName:bundle:)

+4


source







All Articles