3

I have been looking for a a way to instantiate a custom UIViewController class which is not attached to a storyboard or xib file.

Naturally, when I try to initialize the UIViewController it's expecting an NSCoder object.

However I have no idea where this NSCoder object comes from or how to properly make it. The documentation says its an interface declaration object.

Do you know how I can make an NSCoder object that will let me initialize my UIViewController or is there an NSCoder object somewhere in the application I can fetch?

public class Controller:UIViewController, UIAlertViewDelegate
{
    var _viewAuto:AutoUI! //newName

    override init()
    {
        super.init()
    }

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

enter image description here enter image description here

Aggressor
  • 13,323
  • 24
  • 103
  • 182

1 Answers1

1

init(coder aDecoder: NSCoder) is only ever called when a view is instantiated from a storyboard. To create a custom UIViewController and instantiate in manually, all you need to do is add:

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

to your custom view controller. Now you're free to create your own initialization method and pass it whatever variables you like.

kellanburket
  • 12,250
  • 3
  • 46
  • 73
  • I have this and it still wont let me init it without a coder. – Aggressor Feb 26 '15 at 19:09
  • I updated my question with my code, and when I try to instantiate a UIViewController. It wont let me init it without the coder still. I cant just use () – Aggressor Feb 26 '15 at 19:11
  • That's odd. Can you post the code from class where the initializing is happening? I'm assuming C_NewPhotoEditor is a Controller--on a sidenote, UIAlertViewDelegate is deprecated as of IOS8, so you shouldn't be using it at all. – kellanburket Feb 26 '15 at 19:14
  • The init is the same as the Controller, its just a subclass with the same empty init call. – Aggressor Feb 26 '15 at 19:21
  • I mean what is the type of C_NewPhotoEditor? I just compiled your code without any errors or warning, so C_NewPhotoEditor must not conform in some way to your example there. Are you sure C_NewPhotoEditor's type isn't just a UIViewController? – kellanburket Feb 26 '15 at 19:23
  • Controller is a subsclass of UIViewController, as is C_NewPhotoEditor – Aggressor Feb 26 '15 at 19:23
  • Ive added the class signature – Aggressor Feb 26 '15 at 19:24
  • 1
    Did you override init() in C_NewPhotoEditor, too? – kellanburket Feb 26 '15 at 19:34
  • Yes I had added required public override init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeVars() } – Aggressor Feb 26 '15 at 19:37
  • When I removed this it worked, thank you. I am moving away from storyboards and it seems this (legacy code) was forcing it to still required a coder – Aggressor Feb 26 '15 at 19:38