在创建获取的结果控制器时出错。如果您通过指定 sectionNameKeyPath:@"completed" 将结果分组到多个部分,那么您必须使用相同的键添加第一个排序描述符:
NSSortDescriptor *completeSort = [[NSSortDescriptor alloc] initWithKey:@"completed" ascending:YES];
NSSortDescriptor *daySort = [[NSSortDescriptor alloc] initWithKey:@"dateCreated" ascending:YES];
[dayRequest setSortDescriptors:[NSArray arrayWithObjects:completeSort, daySort, nil]];
另一个问题在tableView:cellForRowAtIndexPath:
[self configureCell:cell atIndexPath:indexPath];
[cell formatCell:indexPath.section];
这里假设第 0 部分包含所有带有 completed = NO 的项目,而第 1 部分包含所有带有 completed = YES 的项目。但如果所有项目都完成了,那么只有一个部分(第 0 部分)包含所有已完成的项目。所以你不能使用indexPath.section 作为formatCell 的参数。您应该改用goal.completed 的值。例如,您可以将formatCell 调用移动到configureCell:atIndexPath: 方法中:
- (void)configureCell:(RegimenCell *)cell atIndexPath:(NSIndexPath *)indexPath {
RegimenGoal *goal = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.label.text = goal.text;
[cell formatCell:goal.completed.intValue];
}
现在让表格单元格reuseIdentifier 依赖于节和行号没有多大意义。我认为您可以替换
NSString *CellIdentifier = [NSString stringWithFormat:@"%d-%d", indexPath.row, indexPath.section];
通过固定字符串
NSString *CellIdentifier = @"YourCellIdentifer";
setNavTitle 方法中也存在类似问题:
int goalsCount = [_tableView numberOfRowsInSection:0];
int completedCount = [_tableView numberOfRowsInSection:1];
同样,如果所有目标都已完成,则它们都在第 0 节中,并且没有第 1 节。在这种情况下,您当前的代码将显示“(0%)”而不是“(100%)”。
补充说明:
- “移动的对象有时报告为已更新”解决方法在这里似乎没有必要。
- 对于
NSFetchedResultsChangeUpdate 事件,您可以调用[self configureCell:...] 或[[_tableView reloadRowsAtIndexPaths:...]。无需调用两者。
- 实例变量
_fetchedResultsController 只能在fetchedResultsController 方法中使用,该方法根据需要创建获取结果控制器(FRC)。在所有其他地方,您应该使用self.fetchedResultsController 以确保在必要时创建 FRC。