您好我创建了UIView子类MightyPickerView,它是从xib加载的。
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[MightyPickerView class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
到目前为止,这个功能也非常好,我在以前的许多项目中都使用了这个,没有任何问但现在我想创建名为TimePickerView
的MightyPickerView的子类。
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame]; // here's the problem
if (self) {
[self setupSizes];
}
return self;
}
当我运行应用程序时,它会崩溃
[MightyPickerView setupSizes]: unrecognized selector sent to instance 0x137e53660
问题是此行self = [super initWithFrame:frame];
返回MightyPickerView而不是TimePickerView。
我应该如何编写MightyPickerView的初始化程序,以便在需要时返回子类。
答案 0 :(得分:0)
你所做的事情毫无意义。你不应该误用initWithFrame
让你的视图转向并从笔尖加载自己。如果要从笔尖加载MightyPickerView,请从笔尖加载它,即让一些其他类说[[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:nil options:nil];
并拉出视图。要封装,可以使用类工厂方法。不要在init
内进行这种愚蠢的自我替换。它可能显然是有效的,但它总是错误的行为,现在又回来咬你了。