我有两个 UIView。它们都需要自定义初始化,而且在 initWithFrame: 和 initWithCoder: 中简单地复制初始化代码似乎重复且容易出错。但是,具有像 initMyStuff 这样的标准初始化方法名称会导致子版本被调用两次。我可以通过为每个类赋予一个唯一的初始化名称(如 initStuffForCustomViewParent)来解决此问题,但如果有一种方法可以维护标准的自定义初始化方法名称以使我的代码更具可读性,我更愿意这样做。这是该问题的示例实现:
@implementation CustomViewParent
-(id)initWithFrame:(CGRect)aRect
{
if(self=[super initWithFrame:aRect])
[self initMyStuff];
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder])
[self initMyStuff];
return self;
}
-(void)initMyStuff
{
// Do stuff (never called)
}
@end
@implementation CustomViewChild
-(id)initWithFrame:(CGRect)aRect
{
if(self=[super initWithFrame:aRect])
[self initMyStuff];
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder])
[self initMyStuff];
return self;
}
-(void)initMyStuff
{
// Do stuff (called twice)
}
@end
// SAMPLE
// Calls CustomViewChild's initMyStuff twice and CustomViewParent's initMyStuff never
CustomViewChild *obj = [[CustomViewChild alloc] init];