简体   繁体   中英

Custom init method on ViewController to be called before viewDidLoad

I have a custom container view controller that I instantiate from a storyboard and that has a bunch of methods that modify the content of subviews that I've set outlets to from the storyboard.

There are a bunch of ways that I might instantiate this ViewController, and at present I have to make sure that, however I instantiate it, I either display it, explicitly call loadView , or access its .view property before I start doing anything that uses its outlets (since they're all null pointers until loadView is called).

Ideally, I'd like to put a call to loadView or .view in a single initialiser method of my ViewController to get around this problem, rather than having to put the call to .view in a bunch of different places where I initialise the ViewController from.

Does the UIViewController class have a designated initialiser? If not, what methods do I need to modify with my custom initialisation logic to ensure that it will be called on initialisation of my ViewController no matter what?

awakeFromNib seems to be a suitable place for your purpose. From the documentation:

During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController ) are initialized using their initWithCoder: method.
...
After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects.

You can override these to cover the init cases:

- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self customInit];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self customInit];
    }
    return self;
}

- (id)init
    {
        self = [super init];
        if (self) {
            [self customInit];
        }
        return self;
    }

- (void) customInit
{
    //custom init code
}

However this is not good practice and you should do your subview manipulation in viewDidLoad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM