Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone CoreData: How to group fetched results by day?

I am developing an iPhone App with CoreData. One of my entities has an NSDate property named 'time'. It stores times to the minute/second. As my sections i'd like to have the date to the day. So if there are to entries '2010-06-14 8:00' and '2010-06-14 11:00', i'd like them to be grouped to '2010-06-14'.

Currently I just use @"time" as my sectionNameKeyPath:

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

Is there a trick to group by the time to the day? Or do I have to use plain SQL and something like "GROUP BY date(time, '%Y-%m-%d')"?

like image 983
Anonymous Avatar asked Jun 14 '10 13:06

Anonymous


1 Answers

Solved it this way:

Added method - (NSString *)day; to my Entity class with an implementation like this:

- (NSString *)day {
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateStyle = NSDateFormatterFullStyle;

    return [dateFormatter stringFromDate:self.time];
}

Then I used @"day" as sectionNameKeyPath in the initialization of aFetchedResultsController instead of @"time" (see above).

like image 132
Anonymous Avatar answered Oct 23 '22 12:10

Anonymous