无法从其数据源获取单元格 [英] Failed to obtain a cell from its DataSource

查看:27
本文介绍了无法从其数据源获取单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有什么问题

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

但我无法从其数据源获取单元格

整个异常是

*** 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>)'

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

I have set delegate and data source for the table view

推荐答案

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

Your error suggests that cellForRowAtIndexPath is returning nil for some reason, and I'm guessing it's because you are failing to dequeue a reusable cell. If you want to confirm this, just set a breakpoint after your current dequeue call: I expect you'll find cell is set to nil.

如果您使用的是现代 Xcode 模板,您可以在其中获得为您制作的原型单元格,您可能应该改用它:

If you're using modern Xcode templates where you get a prototype cell made for you, you should probably be using this instead:

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

如果您没有使用 Xcode 模板,无论如何都要使用该行代码,然后像这样注册您自己的重用标识符:

If you aren't using an Xcode template, use that line of code anyway then register your own re-use identifier like this:

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

一切都很好,应该可以解决问题.我为 Swift 用户更详细地写了这篇文章.

All being well that should resolve the problem. I wrote this up in more detail for Swift users.

这篇关于无法从其数据源获取单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆