目标C:我的自定义-init方法没有被调用

时间:2011-11-20 01:46:53

标签: objective-c cocoa-touch

我有一个我从UIView派生的类,我想为它创建一个-init类:

- (id) init
{
    if (self = [super init]) {
        // my initializations here
    }
    return self;
}

不幸的是,我知道一个事实 - 没有被调用。以下是我在.h中的定义方式:

-(id)init;

有人知道为什么没有被召唤?

附录:

我发现当我在initWithCoder中进行初始化时,它运行得很好。 我添加了initWithFrame,但没有调用它。

这是我在IB中指定的对象。

1 个答案:

答案 0 :(得分:13)

UIViewControllerUIView有两个指定的初始值设定项initWithCodernib调用,initWithFrame从代码调用。 Init不是这些对象的指定初始值设定项。

如果你想覆盖这两个基础,你可以这样做:

-(void)initializationCodeMethod{
    <#Initialization Code Here#>
}
-(id)initWithFrame:(CGRect)frame{
    if ((self = [super initWithFrame:frame])){
        [self initializationCodeMethod];
    }
    return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
    if ((self = [super initWithCoder:aDecoder])){
        [self initializationCodeMethod];
    }
    return self;
}