我有以下代码,我相信 NSFetchRequest
实际上正在工作,但在 viewWillAppear
运行后,我的 tableView(peopleList) 中没有显示任何内容。
-(void)viewWillAppear:(BOOL)animated{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error = nil;
NSLog(@"Count for request is %a", [moc countForFetchRequest:request error:&error]);
personArray = [moc executeFetchRequest:request error:&error];
[peopleList reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier];
}
NSString *cellValue = [personArray objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
为了以防万一,我的 Storyboard如图所示连接。
我的控制台显示“请求计数为 23”,这让我认为故障出在让数组本身显示在界面中的某个地方。需要做什么才能让我的 personArray 出现在 peopleList 中?
感谢任何帮助。
最佳答案
您需要声明一个 UITableViewDataSource,它是一个实现该协议(protocol)并向表提供数据的对象。这是调用 cellForRowAtIndexPath 的部分。它常常是 self 的,即tableViewController 类,因为它通常将数组作为局部变量。
myTableView.dataSource = self;
在你的头文件中,执行如下操作:
@interface myTableViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource> {
}
关于iphone - 为什么我的 tableView 没有加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321102/