Reputation: 154585
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?
Upvotes: 1
Views: 6654
Reputation: 539685
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 ofUIView
andUIViewController
) are initialized using theirinitWithCoder:
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 theawakeFromNib
method of the objects.
Upvotes: 3
Reputation: 1725
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.
Upvotes: -1