You would have roughly to do the following:
Add a first sort descriptor on the date
attribute to the fetch request.
Add a transient property "sectionIdentifier" to the Person entity,
and implement a custom getter - (NSString *)sectionIdentifier
to the Person
managed object subclass, that returns
"0", "1", "2", "3", or "4", depending on the date
attribute of the object.
Set sectionNameKeyPath:@"sectionIdentifier"
in the creation of the fetched results controller.
Add a titleForHeaderInSection
method to the table view controller, that
returns "Today", "Tomorrow", ... depending on the section.
The DateSectionTitles sample project from the Apple Developer Library also demonstrates how this works.
The sort descriptors would then look like this:
// First sort descriptor (required for grouping into sections):
NSSortDescriptor *sortByDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
// Second sort descriptor (for the items within each section):
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"firstname" ascending:YES];
[request setSortDescriptors:@[sortByDate, sortByName]];
The getter method for the transient "sectionIdentifier" property would look like
(adapted from the "DateSectionTitles" sample code):
- (NSString *)sectionIdentifier
{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp)
{
NSDate *date = self.date;
// Using pseudo-code here:
if ("date is from today") {
tmp = @"0";
} else if ("date is from tomorrow") {
tmp = @"1";
} else ... // and so on ...
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
return tmp;
}
To determine if the date falls on today, tomorrow etc you have to use NSCalendar
methods.
The titleForHeaderInSection
method would be similar to this (untested, as
everything else in this answer):
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
NSString *sectionName = [theSection name];
if ([sectionName isEqualToString:@"0"]) {
return @"Today";
} else if ([sectionName isEqualToString:@"1"]) {
return @"Tomorrow";
} ... // and so on ...
} else {
return @"Other";
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…