【发布时间】:2014-03-05 04:28:19
【问题描述】:
我有两个自定义单元格。我想在我的UITableView 中显示 2 个部分。第一部分显示第一个自定义单元格,第二部分显示从核心数据中提取的对象列表。
我应该如何实现“cellForRowAtIndexpath”方法?
这是我的一些代码:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return 1;
} else if (section == 1) {
//gastos is an array
return [self.gastos count];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
case 0:
{
SaldoCelda *cell1 = [tableView dequeueReusableCellWithIdentifier:@"Cell1" forIndexPath:indexPath];
return cell1;
}
case 1:
{
static NSString *CellIdentifier = @"Cell";
CeldaGasto *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSManagedObject *gasto = [self.gastos objectAtIndex:indexPath.row];
[cell.monto setText:[NSString stringWithFormat:@"%@ AR$", [gasto valueForKey:@"monto"]]];
[cell.categoria setText:[NSString stringWithFormat:@"%@", [gasto valueForKey:@"categoria"]]];
[cell.fecha setText:[NSString stringWithFormat:@"%@", [gasto valueForKey:@"fecha"]]];
return cell;
}
default:
break;
}
return 0;
}
这是我收到的错误消息:
断言失败 -[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2903.23/UITableView.m:6246 2014-03-05 01:02:57.181 Spendings[2897:70b] * 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“UITableView 数据源必须从 tableView:cellForRowAtIndexPath 返回一个单元格:”
感谢您的帮助!
【问题讨论】:
-
读取错误。您正在为您的
cellForRowAtIndexPath:方法返回nil。要么是 case 0 要么是 case 1。使用调试器,看看哪个是问题所在。 -
顺便说一句 - 一点旁注 - 对于以
return结尾的情况,您的switch中不需要break语句。在这些情况下,将永远无法到达break语句。 -
你是对的!方法结束时返回0可以吗?切换结束后?
-
实际上,
cellForRowAtIndexPath末尾的return 0;应该是return nil;,但从技术上讲,它们是一回事。无论如何,return 0将永远无法到达。 -
@JuanM。必须检查我的答案并尝试过
标签: ios iphone objective-c uitableview custom-cell