简体   繁体   中英

Trying to sort Core Data objects by date in table view

I've got a Core Data setup where each object has an NSDate, and a method that returns the date as a string (ie, "12/15/2009"). The objects are displayed in a table view, and I'd like to sort them into sections based on the date string. Apple's example code in the CoreDataBooks app uses this line:

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

So I altered it and used this line in my project:

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

Where "workoutDateString" is the method that returns a workout object's date as a string. My core data setup works perfectly when I leave sectionNameKeyPath as nil, and I also know that my workoutDateString method works correctly. But when I set sectionNameKeyPath to workoutDateString, not only does it not display the section titles, but every time I add a workout object, the program crashes with this error:

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).'

This is my first real iPhone project and I don't have any experience with setting up table sections. And trust me, I have spent quite a bit of time on Google looking for solutions.

I had this exact same problem, and spent an enormous amount of time researching it.

The NSFetchedResultsControllerDelegate 'animate changes' code causes serious problems when items are added to a completely new section or all the items from a section are moved to another, leaving the original section with 0 items.

I would either remove all the code that does fancy insertion/deletion of sections/rows, or use Jeff LaMarche's code to fix it. http://iphonedevelopment.blogspot.com/2009/11/one-fix-to-nsfetchedresultscontroller.html

EDIT: You implemented [tableView:titleForHeaderInSection], right?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM