Ben Lu
Ben Lu

Reputation: 3042

Will initWithFrame: trigger init?

I made a subclass of UIImageView and I want to add something to be triggered whenever I call initWithFrame or initWithImage or Init...

-(id) init {
  [super init];
  NSLog(@"Init triggered.");
}

If I call -initWithFrame: method, will the -init above be triggered as well?

Upvotes: 8

Views: 2474

Answers (1)

Tom Dalling
Tom Dalling

Reputation: 24125

Every class is supposed to have a designated initialiser. If UIImageView follows this convention (it should, but I haven't tested it) then you'll find that calling -init will end up calling -initWithFrame:.

If you want to ensure that your init method is run, all you have to do is override the designated initialiser of the parent class, either like this:

-(id) initWithFrame:(CGRect)frame;
{
    if((self = [super initWithFrame:frame])){
        //do initialisation here
    }
    return self;
}

Or like this:

//always override superclass's designated initialiser
-(id) initWithFrame:(CGRect)frame;
{
    return [self initWithSomethingElse];
}

-(id) initWithSomethingElse;
{
    //always call superclass's designated initializer
    if((self = [super initWithFrame:CGRectZero])){
        //do initialisation here
    }
    return self;
}

Upvotes: 8

Related Questions