下面的代码有什么问题

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *CellIdentifier  = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    cell.textLabel.text = @"hello";

    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

但我得了failed to obtain a cell from its dataSource

唯一的例外是

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (<UITableView: 0x7ffe0b092800; frame = (0 97; 414 590); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7ffe0acf3b10>; layer = <CALayer: 0x7ffe0aceb6e0>; contentOffset: {0, 0}; contentSize: {414, 88}>) failed to obtain a cell from its dataSource (<AllContactsViewController: 0x7ffe0ace60f0>)'

我已经为表视图设置了委托和数据源

推荐答案

您的错误表明,由于某种原因,cellForRowAtIndexPath返回nil,我猜这是因为您未能将可重用单元出列.如果您想确认这一点,只需在当前的出列调用后设置一个断点:我希望您会发现cell被设置为nil.

如果您使用的是现代Xcode模板,其中有一个为您制作的原型单元,那么您可能应该使用以下内容:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

如果您没有使用Xcode模板,请使用该代码行,然后注册自己的重用标识符,如下所示:

[self.tableView registerClass:[UITableViewCell self] forCellReuseIdentifier:@"Cell"];

一切都很好,应该能解决问题.I wrote this up in more detail for Swift users.

Objective-c相关问答推荐

iOS - 如何预加载键盘?

如何通过仅更改高度而不更改宽度来调整 UILabel 的大小?

如何将变量参数传递给另一个方法?

为什么 NSDateFormatter 为这 4 个时区返回 nil 日期?

NSFileManager 唯一的文件名

从 Unix 时间戳创建 NSDate

块引用作为Objective-C中的实例变量

如何调整 UIModalPresentationFormSheet 的大小?

try 标记应用程序图标但未获得用户标记应用程序的权限:iOS 8 Xcode 6

从我在 iPhone 上的应用程序调用官方 *Settings* 应用程序

Grand Central Dispatch (GCD) 与 performSelector - 需要更好的解释

声音在 iPhone 模拟器中不起作用?

如何删除手势识别器

UIWebView didFinishLoading 多次触发

Cocoapods ld:找不到-lPods-Projectname 的库

无法在导航栏中心设置titleView,因为返回按钮

架构 i386 clang 的重复符号

performFetchWithCompletionHandler 永远不会被解雇

如何获得设备的比例因子?

公开只读但具有私有设置器的 Objective-C 属性