50

im having trouble overriding the initialization method for my CustomViewController thats designed in my Storyboard.

now im doing (in my mainViewController):

self.customViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil] instantiateViewControllerWithIdentifier:@"CustomVC"];
self.customViewController.myObject = someObject;

and i have in viewDidLoad (CustomViewController)

    [self.label setText:self.myObject.someString];

This works ok.

But, is it the correct way? Should i add a custom init method (or override) to my CustomViewController ? Like initWithObject: ? I dont know how to call my custom init method instead of UIStoryboard instantiateViewControllerWithIdentifier:, and im not getting calls to init nor initWithNibName.

Maybe i should use: - (id)initWithCoder:(NSCoder *)decoder.

Please give me some advice!

Thank you!

Nicolas S
  • 5,325
  • 3
  • 29
  • 36
  • you are doing everything right. you can override initWithCoder in your custom class i.e the class file of your _customViewController object for doing custom init – VJ Vélan Solutions Jul 05 '13 at 04:19

2 Answers2

58

The designated initializer for view controllers in storyboards is -initWithCoder:. Since most view controllers from a storyboard are created via segues, you usually see state set during -prepareForSegue:sender:.

If you're instantiating a view controller directly from the storyboard like in the example you provided, then the pattern you've selected is appropriate.

retainCount
  • 4,478
  • 1
  • 22
  • 14
  • Great to know im doing things as supposed to! – Nicolas S Mar 25 '12 at 16:30
  • 2
    That is a pretty bad design, since it makes you make use of Optionals in swift (with !?) or access possible nils if the developer forget to set the correct variable. It is sad that this is the "appropriate" solution: a good source on this issue with swift/objective c optional: http://www.objc.io/issue-16/power-of-swift.html – Guilherme Silveira Oct 16 '14 at 16:31
  • Just to respond to @GuilhermeSilveira comment, this question was from 2012 where swift was not even known to the public, and even if it was, design patterns are way different between Objective-C and Swift so you should not stick to this pattern if you are developing with Swift. – Nicolas S Nov 23 '15 at 20:35
  • Is there a pattern for Swift to avoid optionals or implicitly unwrapped optionals for a VC that's loaded from a Storyboard? – bobics Jan 29 '16 at 00:58
0

As another "workaround" for this problem, you could use delegation. Create a protocol that would act as data source for your UIViewController subclass from storyboard. Conform to this data source protocol, implement it and use it right after loading your UIViewController subclass:

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

        //invoke your data source here
    }

I know... I also don't like this but... ;)

Despotovic
  • 1,807
  • 2
  • 20
  • 24