Search code examples
uinavigationcontrollerswift2

Some seemingly useless cruft when deriving from UINavigationController in swift


Why do I need so much (seemingly useless) pass through code that objc did not require in a similar derivation:

class myNavigationController: UINavigationController {

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

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

repeat ad nauseam for every single view controller of mine loaded from xib.


Solution

  • This should not be an issue if your don't want to overload the designated initializer init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) your UINavigationController subclass. If you just want to make use of the default (super) initializer, you can remove both those methods from your class.

    I.e., the following class

    // MyNavigationController.swift
    import UIKit
    
    class MyNavigationController: UINavigationController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // I don't want to make use of this ...
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // ... nor this
        }
    
        // Things I do want to do with my nav. controller
    }
    

    can be reduced to

    // MyNavigationController.swift
    import UIKit
    
    class MyNavigationController: UINavigationController {
    
        // Things I do want to do with my nav. controller
    }
    

    Without any errors. (Verified in Swift 2.0, Xcode 7.2, simulator: iOS 9.2). This is expected behavior, see e.g. the accepted answer in thread 'required' initializer 'init(coder:)' must be provided by subclass of 'UITableViewCell'`.

    If you still get an error when removing these for this subclass type, please give some details regarding your use of the class / Xcode version etc.