类簇初始化
我的iPhone应用程序有一个抽象类WorkingView。它是 UIView 的子类。反过来,WorkingView 将有一堆具体的子类。其中两个是 SimplifyView 和 MultiplyView。
我正在尝试编写创建工作视图新实例的方法。该方法应该传入模式并返回适当的具体子类的实例。根据这个问题的答案,这就是我到目前为止所得到的:
+ (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;
}
到目前为止,一切都很好。但问题就在这里。在SimplifyView的init方法中,我需要通过UIView的init方法来运行该对象。调用 [super initWithFrame:frame] 只会让我进入WorkingView,而不是一直进入UIView。我想我可以在WorkingView 中创建一个initWithFrame: 方法,该方法又调用UIView 的initWithFrame: 方法——但这感觉很hackish。
处理这个问题的适当方法是什么?
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 instances 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您从子类调用
[super initWithFrame:frame]
,运行时将爬升继承层次结构,寻找实现该方法的类,从 super 开始。如果 super 没有实现initWithFrame:
,运行时将继续爬升,直到最终找到并调用 UIView 中的默认实现。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 implementinitWithFrame:
, the runtime will keep climbing until it eventually finds and invokes the default implementation in UIView.