Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
Ben Lu Avatar asked Dec 21 '11 09:12

Ben Lu


1 Answers

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;
}
like image 50
Tom Dalling Avatar answered Sep 22 '22 08:09

Tom Dalling