Hampotato
Hampotato

Reputation: 267

Is it possible to override a designated initializer with a convenience initializer?

Some one wants to override UITableViewController's designated initializer - (instancetype)initWithStyle:(UITableViewStyle)style. He added the following code:

- (instancetype)initWithStyle:(UITableViewStyle)style {
    self = [self init];

    return self;
}

and gets 2 warnings :

  1. Designated initializer should only invoke a designated initializer on 'super'
  2. Designated initializer missing a 'super' call to a designated initializer of the super class

It might be a bad practice to do so. However, is it possible at all to override a designated initializer with a convenience initializer without raising warnings?

Thanks!

Upvotes: 2

Views: 580

Answers (1)

Bamsworld
Bamsworld

Reputation: 5680

This is possible but there are several conditions that must be met in order to get no compiler warnings. ALL designated initialisers for the sub-class must be overridden, also use the NS_DESIGNATED_INITIALIZER macro to mark what init.. methods are to be treated as designated initialisers.

The following is for a sub-class of UITableViewController -

.h

- (instancetype)initWithStyle:(UITableViewStyle)style;// this is no longer a designated initialiser

- (instancetype)init NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

.m

- (instancetype)initWithStyle:(UITableViewStyle)style {
//.. no longer treated as designated initialiser
self = [self init];

return self;
}

- (instancetype)init {
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        //.. this is now treated as designated initialiser
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        //.. must implement
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        //.. must implement
    }
    return self;
}

Additional info is found in Adopting Modern Objective-C under Object Initialization.

Upvotes: 0

Related Questions