7

I have a nib-based table view cell which I created in Interface builder. I set the class of the table view cell to FooTableViewCell which extends from UITableViewCell.

In FooTableViewCell I override the init method like this:

-(id)init{

    if ((self = [super init])){
      // My init code here
    }
    return self;
}

I now expected that my gets called, when it is being instantiated. However the table view gets displayed but the method is never called.

I could work around this but I would like to fully understand it and for me it's not clear how an object can come to live without the init method being called.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Besi
  • 22,579
  • 24
  • 131
  • 223
  • if you load your cell from nib file the way you posted you don't need 'cell = [[StationAndTwoProgramsCell alloc] init]; ' line - as created with alloc/init cell will get overwritten anyway in the next line 'cell = ...' and that will also result in memory leak. – Vladimir Aug 04 '11 at 13:23

2 Answers2

19

When being unarchived initialization goes through a slightly different path.

Instead of -(id)init being called -(id)initWithCoder:(NSCoder*)aDecoder will be called. At this point outlets aren't hooked up, if you need access to the outlets you can override -(void)awakeFromNib which will be called after the object has been hooked up.

FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
  • You're a lifesaver! Been trying to find a way of 'defaulting' all of my custom cells background colours from a custom superclass. This worked great! – Adam Carter Aug 18 '12 at 16:16
7

When object is being loaded from nib file then its -awakeFromNib method is called - you can put your initialisation code there:

- (void)awakeFromNib{
   // Init code
}
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
Vladimir
  • 170,431
  • 36
  • 387
  • 313