initWithStyle:(UITableViewStyle)style looks not called

3.5k Views Asked by At

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;
1

There are 1 best solutions below

2
On

"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;
}