Core Data sort tableview by formatted date

不羁的心 提交于 2019-12-06 16:05:04

(I'll write this up assuming you're using an NSFetchedResultsController to drive your tableview. If you're not, I recommend checking it out.)

An interesting feature of NSFetchedResultsController's sectioning abilities: although the property you sort on must be a modeled property (because sqlite does the actual sorting), the property you group the sections with need not be. The only requirement is that the grouping be consistent with the ordering. (i.e., sorting by the sort property will put the objects with matching group properties next to each other.)

So just add something like this to your modeled object class:

// in interface
@property (nonatomic, readonly) NSString *mediumFormattedDate;

// in impl
-(NSString *)mediumFormattedDate
{
  // this can be fancier if you need a custom format or particular timezone: 
  return [NSDateFormatter localizedStringFromDate:self.date
                                        dateStyle:NSDateFormatterMediumStyle
                                        timeStyle:NSDateFormatterNoStyle];
}

(no need to mention mediumFormattedDate in the .xcdatamodel at all.)

Then go ahead and sort your objects by the date property, but group them by your new property. When you create your NSFetchedResultsController, do so along these lines:

NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"MyFancyEntity"];
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"date"
                                                     ascending:YES];
[fr setSortDescriptors:[NSArray arrayWithObject:sd]];
NSFetchedResultsController *frc =
[[NSFetchedResultsController alloc] initWithFetchRequest:fr
                                    managedObjectContext:myManagedObjectContext
                                      sectionNameKeyPath:@"mediumFormattedDate"
                                               cacheName:nil];
// then do stuff with frc

That's all it takes! I've done this in a few apps to get date grouping and it works well.

Sounds like you're setting the section index on the fetched results controller to be your date property, which seems undesirable.

Instead you should probably be computing the section index yourself, and sorting by date. You can accomplish this in either your data model or by computing the sections manually in code.

For example, you could add a property to your managed object model called "Day" and set that to whatever value you want to use (you don't specify if its something like Monday or an actual date like 21).

You can then pass that property to the fetched results controller.

Alternatively you could implement the sections yourself, days are easy, its Monday-Sunday. Dates are a bit harder, 1-28,30,31 depending on what month it is. Then use an appropriate NSPredicate / NSFetchRequest to get the count of the items in each section.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!