In my Core Data Model i\'ve got an entity that has a date attribute and as the title suggests, i\'d like to group this entity by (week)days.
The problem is, the dates ar
If you want to group by weekday, the easiest thing to do is to add an attribute such as "weekday" to your entity; then you pass "weekday" as sectionNameKeyPath argument when initializing the NSFetchedResultsController. In this case there is no need to specify a predicate: you will automatically get sections for the weekdays.
If you want to group by day, you pass DateAttribute as sectionNameKeyPath argument when initializing the NSFetchedResultsController. Again, there is no need to specify a predicate: you will automatically get sections for the days.
What you are trying to do in your code differs from what you asked for. Indeed, you are not trying to get back sections (i.e. grouping by an attribute): you are instead trying to get back a single section for your tableView containing objects described by your entity satisfying a specific predicate, namely the ones whose DateAttribute falls (probably) in the current day. To achieve this, you can use the following code:
// start by retrieving day, weekday, month and year components for today
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
// now build a NSDate object for the input date using these components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate *thisDate = [gregorian dateFromComponents:components];
[components release];
// now build a NSDate object for tomorrow
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:thisDate options:0];
[offsetComponents release];
NSDateComponents *tomorrowComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:nextDate];
NSInteger tomorrowDay = [tomorrowComponents day];
NSInteger tomorrowMonth = [tomorrowComponents month];
NSInteger tomorrowYear = [tomorrowComponents year];
[gregorian release];
// now build the predicate needed to fetch the information
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"DateAttribute < %@ && DateAttribute > %@", nextDate, thisDate];
This predicate will retrieve exactly all of the objects whose DateAttribute falls within the current day. Hope this helps.