我有一个NIB文件,用类(SomeClassView:UIView的)设置为自定义类的NIB的顶层视图。 SomeClass有IBOutlets,用于连接我在Interface Builder中布局的SomeClass的子视图。从NIB文件子类的UIView不是打字子类
我实例SomeClass的是这样的:
- (id)initWithFrame:(CGRect)frame {
self = [[[[NSBundle mainBundle] loadNibNamed:@"SomeClassView" owner:nil options:nil] objectAtIndex:0] retain];
// "SomeClassView" is also the name of the nib
if (self != nil) {
self.frame = frame;
}
return self;
}
现在说我继承SomeClass的与SubClassView。我添加到SubClassView调用的方法 - (空)富:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self != nil) {
[self foo];
}
return self;
}
在这一点上,我得到一个运行时错误:*终止应用程序由于未捕获的异常“NSInvalidArgumentException”,原因是:“ - [SomeClassView富: ]:无法识别的选择器发送到实例0xAAAAAA'
似乎在SubClassView的initWithFrame内的“自我”仍然设置为超级SomeClassView。快速破解补丁来解决,这是改变SubClassView initWithFrame内的isa指针:
- (id)initWithFrame:(CGRect)frame {
Class prevClass = [self class];
self = [super initWithFrame:frame];
if (self != nil) {
isa = prevClass;
[self foo]; // works now
}
}
这不是一个理想的解决办法,因为我每次我继承的时间来更新ISA,或者甚至有可能是不同的init方法我也必须更新。
1)理想情况下,有一种简单的方式来解决这个问题,仅仅通过代码?也许用我设置self =装载的笔尖的方式?
2)是否有适用于我想要做的更好的替代架构?一个例子是将所有者设置为self,但是您必须手动设置所有的property/outlet映射。
谢谢,我更新了第三段代码。我认为我接受这样一个事实,即通过继承来改变笔尖类型是没有意义的。 – roblocop 2011-04-06 04:08:24
@roblocop虽然它会很有用。我认为它保证提交一个改进请求雷达。 – 2011-04-06 04:16:49
@Bavarious,你还是推荐这个实现,或者现在我们在2015年有更好的实现。 – 2015-09-22 13:17:33