Why can't I call super.init () on a UIViewController in Swift by default?

I do not use the UIViewController from StoryBoards, and I want to have a custom init function, where I pass the NSManagedObjectID of some object. I just want to call super.init (), as in lens c. Like this:

init(objectId : NSManagedObjectID) { super.init() } 

But I can’t compile with this. Can I just not do it anymore?

The compiler error message I get is: "must invoke the designated uiviewcontroller supervisor initializer"

+44
ios objective-c uiviewcontroller ios8 swift
Jun 07 '14 at 7:48
source share
4 answers

The designated initializer for the UIViewController is equal to initWithNibName:bundle: You should call it instead.

See http://www.bignerdranch.com/blog/real-iphone-crap-2-initwithnibnamebundle-is-the-designated-initializer-of-uiviewcontroller/

If you don't have a bottom, go to nil for nibName (the package is also optional). You can then create a custom view in loadView or by adding subviews to self.view in viewDidLoad , as before.

+67
Jun 07 '14 at 7:54 on
source share

Another nice solution is to declare the new initializer as a convenience initializer as follows:

 convenience init( objectId : NSManagedObjectID ) { self.init() // ... store or user your objectId } 

If you do not specify designated initializers at all in your subclass, they are inherited automatically, and you can use self.init() in your convenient initializer.

In the case of the UIViewController, the init method will call init by default init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) With nil for both arguments (Command-Click on the UIViewController will give you this information).

TL; TR . If you prefer to programmatically work with the UIViewController , here is a complete working example that adds a new initializer with a custom argument:

 class MyCustomViewController: UIViewController { var myString: String = "" convenience init( myString: String ) { self.init() self.myString = myString } } 
+31
Aug 15 '14 at
source share

According to the documentation for iOS, the designated initializer for the UIViewController is initWithNibName: bundle:

If you subclass the UIViewController, you must call the super implementation of this method, even if you are not using NIB.

You can do it as follows:

 init(objectId : NSManagedObjectID) { super.init(nibName: (xib name or nil'), bundle: nil) // other code... } 

or

Declare a new initializer as a convenience initializer:

  convenience init( objectId : NSManagedObjectID ) { self.init() // other code... 

}

+2
Jun 24 '17 at 3:48
source share

To improve the oculus response:

 init() { super.init(nibName: nil, bundle: nil) } 
+1
Sep 29 '17 at 13:33
source share



All Articles