开发者

Class cluster initialization

My iPhone app has an abstract class WorkingView. It is a subclass of UIView. WorkingView will in turn have a bunch of concrete subclasses. Two of those will be SimplifyView and MultiplyView.

I am trying to write the method that creates new i开发者_运维问答nstances of WorkingView. This method should have the mode passed in and return an instance of the appropriate concrete subclass. Per the answer to this question, this is what I have so far:

+ (id)newWorkingViewWithFrame:(CGRect)frame mode: (modeEnum) mode {
    WorkingView *ret;
    switch (mode) {
        case simplifyMode:
            ret = [[SimplifyView alloc]initWithFrame: frame];
            break;
        case multiplyMode:
            ret = [[MultiplyView alloc]initWithFrame: frame];
            break;
        // additional cases here
        default:
            return nil;
    }
    // more initialization here
    return ret;
}

So far, so good. But here is the problem. In SimplifyView's init method, I need to run the object through UIView's init method. Calling [super initWithFrame: frame] gets me only to WorkingView, not all the way to UIView. I suppose I could create an initWithFrame: method in WorkingView that in turn calls UIView's initWithFrame: method -- but that feels hackish.

What is the appropriate way to handle this?


If you call [super initWithFrame:frame] from your subclass, the runtime will climb the inheritance hierarchy looking for a class that implements that method, starting with super. If super doesn't implement initWithFrame:, the runtime will keep climbing until it eventually finds and invokes the default implementation in UIView.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜