我有一个问题,我已经在互联网上搜索了解决方案,但无济于事。 我正在关注Apress的开始iOS 5开发的第10章,这是在故事板上。
我认为这本书缺少一段简单的代码,因为我是第一次经历这个,我不知道如何解决它。
我已经重新启动了该项目两次,但在调试器中不断收到此错误:
由于未捕获的异常"NSInternalInconsistencyException"而终止应用程序,原因:"UITableView 数据源必须从 tableView:cellForRowAtIndexPath:' 返回一个单元格
#import "BIDTaskListController.h"
@interface BIDTaskListController ()
@property (strong, nonatomic) NSArray *tasks;
@end
@implementation BIDTaskListController
@synthesize tasks;
- (void)viewDidLoad {
[super viewDidLoad];
self.tasks = [NSArray arrayWithObjects:
@"Walk the dog",
@"URGENT:Buy milk",
@"Clean hidden lair",
@"Invent miniature dolphins",
@"Find new henchmen",
@"Get revenge on do-gooder heroes",
@"URGENT: Fold laundry",
@"Hold entire world hostage",
@"Manicure",
nil];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.tasks = nil;
}
//
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [tasks count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = nil;
NSString *task = [self.tasks objectAtIndex:indexPath.row];
NSRange urgentRange = [task rangeOfString:@"URGENT"];
if (urgentRange.location == NSNotFound) {
identifier = @"plainCell";
} else {
identifier = @"attentionCell";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
UILabel *cellLabel = (UILabel *)[cell viewWithTag:1];
cellLabel.text = task;
return cell;
}
@end
缺少代码:
。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *label = [[UILabel alloc] initWithFrame:cell.bounds];
label.tag = 1;
[cell addSubview:label];
}
UILabel *cellLabel = (UILabel *)[cell viewWithTag:1];
cellLabel.text = task;
....
实际上,我认为您的原始问题不是代码中缺少任何内容,而是您的故事板配置中缺少任何东西!IIRC,该书描述了在故事板中创建两个单元格原型:一个是红色文本,其标识符设置为"attentionCell",另一个是黑色文本,其标识符设置为"plainCell"。如果这两个单元格存在于情节提要的表视图中,并且设置了正确的标识符,则您发布的原始代码段应该可以正常工作。
没有丢失的代码。我完全按照第 10 章中的说明进行操作,它编译并运行良好。
第 363 页的顶部说明,从情节提要加载的表视图可以按需创建单元格,并且无需检查 nil 返回。