D
D
Dmitry Purtov2016-05-23 14:59:52
Objective-C
Dmitry Purtov, 2016-05-23 14:59:52

Subclasses and methods with the same name. How to be?

Task:
There is a ViewA class and ViewB inherited from it with 2 designated initializers each. Both have a configure method called from each initializer:

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self configure];
    }
    return self;
}
//...
- (void)configure {
    // Create some subviews etc
}

The essence of the problem:
  • If we call -configure from the ViewA and ViewB init's, then ViewB's configure init will be called. Calling [super configure] inside -configure does not help (-configure ViewA will be called several times).
  • Checks for -isMemberOfClass when calling -configure from init's work, but add a bunch of extra code
  • Checks for -isMemberOfClass in -configure don't work at all.
  • At the same time, in our application, we want to use both VIewB and ViewA, so not calling -configure from ViewA's init is not an option.

Of course, there is a working and simple solution - to call -configure manually after creating the object:
ViewA *view = [[ViewA alloc] initWithFrame:someFrame];
[view configure];

But this approach does not seem right to me. And I have a feeling that I'm missing something.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question