The apple sample project DateSectionTitles demonstrates how to group sections by year and month, how to extends it to support year month day and weekday?
sectionIdentifier
is a transient attribute derives from persistent date attribute timestamp
.
- (NSString *)sectionIdentifier {
// Create and cache the section identifier on demand.
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp) {
/*
Sections are organized by month and year. Create the section identifier
as a string representing the number (year * 1000 + month);
this way they will be correctly ordered chronologically regardless of
the actual name of the month.
*/
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit)
fromDate:[self timeStamp]];
tmp = [NSString stringWithFormat:@"%d", [components year] * 1000 + [components month]];
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
/*
Section information derives from an event's sectionIdentifier, which is a string representing the number (year * 1000) + month.
To display the section title, convert the year and month components to a string representation.
*/
static NSDateFormatter *formatter = nil;
if (!formatter)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:[NSCalendar currentCalendar]];
NSString *formatTemplate = [NSDateFormatter dateFormatFromTemplate:@"MMMM YYYY" options:0 locale:[NSLocale currentLocale]];
[formatter setDateFormat:formatTemplate];
}
NSInteger numericSection = [[theSection name] integerValue];
NSInteger year = numericSection / 1000;
NSInteger month = numericSection - (year * 1000);
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year = year;
dateComponents.month = month;
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSString *titleString = [formatter stringFromDate:date];
return titleString;
}
I don't know the exact algorithm to calculate year month day and weekday like below code.
tmp = [NSString stringWithFormat:@"%d", [components year] * 1000 + [components month]];
And the calculate for the data source method.
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
NSInteger numericSection = [[theSection name] integerValue];
NSInteger year = numericSection / 1000;
NSInteger month = numericSection - (year * 1000);