如何在Objective C中正确初始化子类?

时间:2012-09-27 18:50:14

标签: iphone objective-c ios uiview initialization

我有两个UIViews。它们都需要自定义初始化,并且在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];

1 个答案:

答案 0 :(得分:7)

CustomViewChild不应致电initMyStuff。只需在父母中调用此内容,并且孩子的initMyStuff应调用[super initMyStuff]

但在任何一种情况下,都不要将其称为initMyStuff,因为这表明它是一种init方法,这意味着某些行为。称之为setup(假设目标是从initWithFrameinitWithCoder:调用它。)