I have the following in a subclass of UIViewController;
- (id) initWithFullScreen
{
self = [super initWithNibName:nil bundle:nil];
if (self)
{
_fullScreen = YES;
}
return self;
}
- (id) init
{
self = [super initWithNibName:nil bundle:nil];
if (self)
{
_fullScreen = NO;
}
return self;
}
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self init];
}
As you can see they aren’t all chained together like recommended as there are two initializers that call the super classes designated initializer. Is this OK to do?
Yes, it’s OK.
A designated initializer isn’t part of the Objective-C language, it’s just a convention. In general, if you route everything through one init method, your don’t have to worry about duplicating code across all the other convenience init methods that you might want to offer.
It also lets you know which init method you should call on the superclass when you want to create a subclass. (Your third init method,
initWithNibName...violates this rule, actually. Instead of calling the superclass’s designated initializer, you’re just callinginit.)In your case, declaring an initializer with the method signature
initWithFullScreen:(BOOL)fullScreenand designating it the designated initializer is probably the way to go. And within that you make sure you call the superclass’s designated initializer, which you are.You could then create convenience initializers:
initWithFullScreenandinitWithoutFullScreenif you wanted to; they would both just call your designated initializer. For example:So, it’s OK to break the convention. You may have your reasons. But it’s generally easier to keep your code organized if you stick to it.
Amendment
For extra credit, consider the NSCoding protocol, which requires classes to have an
initWithCoder:method. One might say it violates the rule, since classes which adopt NSCoding and whose superclasses also adopt NSCoding must be prepared to have two paths to initialization: aninitWithCoder:method which calls[super initWithCoder:coder]and the regular designated initializer.