viewController custom init method with storyboard

余生长醉 提交于 2019-12-04 07:39:28

问题


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!


回答1:


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.




回答2:


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... ;)



来源:https://stackoverflow.com/questions/9756504/viewcontroller-custom-init-method-with-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!