创建UITableViewController
的默认视图控制器,在其.m
中,默认的init方法如下
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
// Custom initialization
}
return self;
}
在添加数据源和委托方法的标准过程之后,更正iPhone模拟器上显示的表视图。
我的问题是,当尝试在if
中添加NSLog(@"did init");
时,如下所示
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
// Custom initialization
NSLog(@"did init");
}
return self;
}
但再次运行,did init
不会显示在控制台上。 甚至在if
之前或之后移动NSLog
,两者都不起作用!
怎么了?为什么initWithStyle:(UITableViewStyle)style
不工作?
如果按照迈克尔的建议使用initWithCoder
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"init?");
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
NSLog(@"init done");
}
return self;
}
init?
和init done
工作并在控制台上显示。但也是失败的。
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
实际上,如果删除"initWithCoder",应用程序是可以的。
cellForRowAtIndexPath
代码如下,
- (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;
initWithStyle:
"就是从代码创建UITableViewController。
如果要从情节提要创建对象,则真正调用的方法如下:
- (id)initWithCoder:(NSCoder *)decoder
您还将收到" awakeFromNib
"消息。
编辑以添加:
如果你试图用你的"initWithCoder
"方法做一些事情,也调用"super
",像这样:
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"init?");
self = [super initWithCoder: aDecoder];
if (self) {
NSLog(@"init done");
}
return self;
}