我有 UITableView
显示核心数据项,之前通过数组 Hook 没有任何问题。然后,根据 Apple 和斯坦福的建议,我转向 CoreDataTableViewController
,直接通过 NSFetchedResultsController
将 Core Data 与 UITableView
集成。我已将 CoreDataTableViewController
添加到我的项目并将我原来的 TVC 的父类(super class)更改为新的 CDTVC。
我现在遇到屏幕外单元格的问题,其中一些是灰色的,上面有错误的数据。它可能与重复使用这些单元格有关,但我无法找出解决方案。有任何想法吗?谢谢。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
Period *displayPeriod = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
cell.textLabel.text = [dateFormatter stringFromDate:displayPeriod.date];
NSError *error = nil;
NSUInteger logbookCount = [self.managedObjectContext countForFetchRequest:self.fetchedResultsController.fetchRequest error:&error];
if (indexPath.row == logbookCount - 1) {
cell.detailTextLabel.text = @"";
} else {
int difference;
NSIndexPath *nextRow = [NSIndexPath indexPathForItem:indexPath.row + 1 inSection:indexPath.section];
Period *periodOne = [self.fetchedResultsController objectAtIndexPath:nextRow];
Period *periodTwo = [self.fetchedResultsController objectAtIndexPath:indexPath];
difference = [self dateDiffrenceFromDate:periodOne.date second:periodTwo.date];
cell.detailTextLabel.text = [self formatDifferenceToString:difference];
if (difference > 45 || difference < 21) {
cell.detailTextLabel.textColor = [UIColor colorWithRed:255/255.0 green:59/255.0 blue:48/255.0 alpha:1.0];
} else {
cell.detailTextLabel.textColor = [UIColor colorWithRed:142/255.0 green:142/255.0 blue:147/255.0 alpha:1.0];
}
}
return cell;
}
截图:
最佳答案
我不知道你的情况如何。根据我的意见和您的回答,您在与核心数据相关的内容中看不到任何错误。无论如何,我看不到任何与单元格创建相关的代码。另外,你说你没有使用 registerClass
方法。因此,我会尝试两种解决方案。
以显式方式使用 registerClass
(从 iOS 6 开始)。
- (void) viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier ];
}
或者只是创建带有 if 子句的单元格。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell) {
cell = // create the cell here
}
// configure the cell here
关于ios - 带有 NSFetchedResultController 的 TableView 在屏幕外显示损坏的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616861/