ios - 尝试在表格 View 中按日期对核心数据对象进行排序

标签 ios objective-c iphone uitableview core-data

我有一个核心数据设置,其中每个对象都有一个 NSDate,以及一个将日期作为字符串返回的方法(即“12/15/2009”)。这些对象显示在表格 View 中,我想根据日期字符串将它们分类。 Apple 在 CoreDataBooks 应用程序中的示例代码使用了这一行:

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"author" cacheName:@"Root"];

所以我修改了它并在我的项目中使用了这一行:

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"workoutDateString" cacheName:@"Root"];

其中“workoutDateString”是将锻炼对象的日期作为字符串返回的方法。当我将 sectionNameKeyPath 保留为 nil 时,我的核心数据设置工作得很好,而且我也知道我的 workoutDateString 方法工作正常。但是当我将 sectionNameKeyPath 设置为 workoutDateString 时,它不仅不显示部分标题,而且每次我添加锻炼对象时,程序都会崩溃并出现此错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'

这是我的第一个真正的 iPhone 项目,我没有任何设置表格部分的经验。相信我,我花了很多时间在 Google 上寻找解决方案。

最佳答案

我遇到了完全相同的问题,并花了很多时间研究它。

NSFetchedResultsControllerDelegate 'animate changes' 代码会导致严重的问题,当项目被添加到一个全新的部分或一个部分的所有项目被移动到另一个部分时,原始部分只有 0 个项目。

我要么删除所有执行花式插入/删除部分/行的代码,要么使用 Jeff LaMarche 的代码来修复它。 http://iphonedevelopment.blogspot.com/2009/11/one-fix-to-nsfetchedresultscontroller.html

编辑:您实现了 [tableView:titleForHeaderInSection],对吗?

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[<#Fetched results controller#> sections] objectAtIndex:section];
    return [sectionInfo name];
}

关于ios - 尝试在表格 View 中按日期对核心数据对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1912405/

相关文章:

android - 如何在我的移动应用程序中实现聊天机器人

ios - 我可以在 ViewDidLoad 中加载 UICollectionView 的数据吗?

objective-c - 在 Obj-C 中使用 C 语法调用静态方法?

iphone - 编辑时更改 uitextfield 返回键类型

iphone - 加载网页时 UIWebView 显示错误,Safari 显示完美

ios - 在 Collection View 中显示两个不同的单元格 - Swift 2.0 iOS

ios - TableView 不显示来自 parse.com 的数据

iphone - appendFormat 泄漏

ios - 缓存 URL 图片 iphone UITableview

iphone - 游戏设计 : Checking for object intersection or getting values from accelerometer