Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

divide fetched results NSDate into sections for each single day use core data

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.

like image 421
lancy Avatar asked Jan 29 '12 16:01

lancy


2 Answers

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"];
like image 72
Audun Kjelstrup Avatar answered Nov 20 '22 02:11

Audun Kjelstrup


Please refer to the Apple sample code of "DateSectionTitles", you can search this in the Xcode help. it helps a lot!!

like image 37
flypig Avatar answered Nov 20 '22 04:11

flypig