Re: Why is overriding unavailable designated initializer of super required?
Re: Why is overriding unavailable designated initializer of super required?
- Subject: Re: Why is overriding unavailable designated initializer of super required?
- From: Greg Parker <email@hidden>
- Date: Mon, 10 Aug 2015 13:49:53 -0700
> On Aug 10, 2015, at 1:27 PM, Seth Willits <email@hidden> wrote:
>
>
> I've yet to understand this:
> https://gist.github.com/swillits/3133e114f770947b3cf6
>
>
> If a subclass says that its superclass's designated initializer is unavailable (IOW, the subclass's designated initializer must be used), why does the compiler produce a warning that the superclass's designated initializer must be overridden in the subclass?
>
> If the subclass is going to call super's designated initializer via [super init....] then this subclass override would never get called anyway...
>
> What am I missing?
Convenience initializers.
Consider: a superclass that implements a designated initializer and a convenience initializer, and your subclass that introduces a new designated initializer.
@implementation SomeSuperclass
-(id) init; // designated initializer
-(id) convenienceInitializer {
return [self init];
}
@end
@implementation YourSubclass : SomeSuperclass
-(id) initWithValue:(id)value { // designated initializer
return [super init];
}
@end
Now somebody writes this:
id obj = [YourSubclass convenienceInitializer];
This object will not be correctly initialized. It will never call -initWithValue which is required to initialize YourSubclass properly.
The solution is for the subclass to cover all of its superclass's designated initializers. You can implement it to call your designated initializer with appropriate default values:
@implementation YourSubclass
...
-(id) init { // cover of superclass's designated initializer
// delegate to our designated initializer
return [self initWithValue:nil];
}
@end
or you can implement it to fail at runtime:
@interface YourSubclass
-(id) init NS_UNAVAILABLE;
@end
@implementation YourSubclass
...
-(id) init {
abort(); // or throw or whatever
}
@end
Either approach will pacify the compiler.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden