I know that fetched results controller have the section name key path can divide fetched results into sections. But how could I divide NSDate into sections for each day or each month? Or any other ways to solve this problem? Thanks.
What you need to do is to create a transient property on your data object, and then sort your fetched results accordingly. For a TVGuide I've worked on, I needed to sort results by airDay, and ended up sorting the events by startDate, and using the transient property for section key name path:
In Event.m:
-(NSString*) airDay
{
NSDateFormatter *dayFormatter=[[NSDateFormatter alloc] init];
[dayFormatter setLocale:[NSLocale currentLocale]];
[dayFormatter setDateStyle: NSDateFormatterMediumStyle];
[dayFormatter setDoesRelativeDateFormatting: YES];
return [dayFormatter stringFromDate:self.startDate];
}
The matching fetchrequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:[Database db].managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:
[NSSortDescriptor sortDescriptorWithKey:@"startDate"
ascending:YES],
nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[Database db].managedObjectContext
sectionNameKeyPath:@"airDay"
cacheName:@"SearchEvents"];
Please refer to the Apple sample code of "DateSectionTitles", you can search this in the Xcode help. it helps a lot!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With