XCode iOS - 断言失败

3
我刚开始学习iOS开发。我正在做“开始开发iOS应用程序”教程,但是在“添加数据”部分卡住了。
在将表视图设置为使用“动态原型”并将标识符设置为“ListPrototypeCell”之后,我添加了“cellForRowAtIndexPath”方法,但它崩溃并显示以下错误:

Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (未加载)

2014-08-10 13:35:50.519 ToDoList[8954:60b] *** 在 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] 中的断言故障,/SourceCache/UIKit_Sim/UIKit-2935.137/UITableView.m:5439

2014-08-10 13:35:50.523 ToDoList[8954:60b] *** 终止应用程序,原因:无法使用标识符 ListPrototypeCell 获取可重用单元格 - 必须注册一个 Nib 或类来获取该标识符或在故事板中连接原型单元格'

. . . .

libc++abi.dylib: 以 NSException 类型终止未捕获的异常

我已经按照教程进行操作,但是找不到错误。有人可以建议我错在哪里吗?

在此输入图片描述 在此输入图片描述 代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListPrototypeCell" forIndexPath:indexPath];
    XYZToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];
    cell.textLabel.text = toDoItem.itemName;
    return cell;
}

1
你是否将视图控制器设置为放置此代码的类的名称? - ruthless
添加“异常断点”以停止在引起此问题的行上(应该是dequeueReusableCellWithIdentifier:)。检查您是否在正确的控制器中实现了该方法,并且在Storyboard表控制器中具有正确的类。 - Timur Kuchkarov
1个回答

4

使用:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListPrototypeCell"];

对于故事板,这是您想要的。 如果必要,可以跟进:

   if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ListPrototypeCell"];
    }

编辑:如果您想继续使用dequeueReusableCellWithIdentifier:forIndexPath:,那么在控制器的初始化中,您应该使用registerClass:forCellReuseIdentifier:,根据文档,如果您不使用storyboard。同时,在最新的Xcode版本中,(cell == nil)部分已经变得不必要。


2
如果他正在使用带有动态表格视图单元的故事板,则 dequeueReusableCellWithIdentifier:forIndexPath: 应该可以正常工作,并且实际上是首选的方法,因为它保证会返回一个单元。 - TylerP
我不这么认为。而且,如果他想使用那个版本,他必须使用 registerClass:forCellReuseIdentifier: 注册他的类。所以那个答案是正确的。 - Rikkles
1
使用原型单元格,您无需调用 registerClass:forCellReuseIdentifier:registerNib:forCellReuseIdentifier:。这基本上已经为您完成了。 - TylerP
谢谢@Rikkles,代码片段有效,只要包括if(cell == nil)。但是你能解释一下为什么Apple教程中的代码不起作用吗?这是否意味着我错过了某个步骤? - Jonathan Cakes
我上个星期刚下载了Xcode,但结果发现只有5.1.1版,所以我打算升级并且看看最新版的情况! - Jonathan Cakes
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接