lynk
lynk

Reputation: 153

How do I make a super class's custom init method only internally visible to its subclasses?

I currently have this init method for my superclass:

- (id)initWithFoo:(int)foo;

In a subclass, I have a custom init method that calls its superclass's init, like this. Bar is exclusive to the subclass.

-(id)initWithFoo:(int)foo Bar:(int)bar {
    if (self = [super initWithFoo:foo]){
        _bar = bar;
    }
    return self;
}

I run into problems when I create an instance of the subclass, because the compiler happily suggests the superclass init method in the list of possible initialization methods for my subclass instance, which I definitely do not want.

However, if I remove initWithFoo:(int)foo from the superclass's .h file then the subclasses can no longer use it within their own init methods.

Is there any way around this?

Upvotes: 0

Views: 50

Answers (1)

Yaser
Yaser

Reputation: 408

Yes, you can implement initWithFoo in your superclass and in your child make an "extension" declaration:

@interface SuperClass()
- (instancetype)initWithFoo:(int)foo;
@end

Make sure to place that declaration above @implementation in the .m file of your child

Upvotes: 1

Related Questions