0

create a default view controller of UITableViewController, in its .m, default init method as below

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
    // Custom initialization
    }
return self;
}

after standard procedure to add data source and delegate methods, correct table view shown on iPhone simulator.

my question is, when trying to add NSLog(@"did init"); in if, like below

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
    // Custom initialization
    NSLog(@"did init");
}
return self;
}

but run again, did init not show on console. even move NSLog before or after if, neither doesn't work!

What's the problem? Why initWithStyle:(UITableViewStyle)style not work?

if using initWithCoder as suggested by Michael

- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"init?");
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
    NSLog(@"init done");
}
return self;
}

init? and init done worked and show on console. But a failure as well.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

Actually, if deleting `initWithCoder, app is ok.

Codes at cellForRowAtIndexPath as following,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

NSArray * array = [[temp objectAtIndex:indexPath.section] valueForKey:@"English"];
cell.textLabel.text = [array objectAtIndex:indexPath.row];

if (indexPath.row == 0) {
    cell.textLabel.textColor = [UIColor blueColor];
}

return cell;
S1U
  • 825
  • 2
  • 14
  • 26
  • show the code where you call "`initWithStyle`" to set up your table view controller? or did you put this table view controller into a XIB or storyboard? – Michael Dautermann Sep 21 '13 at 04:58
  • in mainStoryboard, where only one table View controller that's embedded in navigation controller. so `initWithStyle` is in this table view controller's `.m` file. – S1U Sep 21 '13 at 05:33

1 Answers1

3

"initWithStyle:" is what one calls creating a UITableViewController from code.

If you're creating the object from a storyboard, the method that really gets called is this:

- (id)initWithCoder:(NSCoder *)decoder

You'll also get an "awakeFromNib" message too.

EDITED to add:

If you're trying to do something with your "initWithCoder" method, call "super" as well, like this:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    NSLog(@"init?");
    self = [super initWithCoder: aDecoder];
    if (self) {
        NSLog(@"init done");
    }
    return self;
}
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215