NSFetchedResultsController group into sections for every 4 hours
I'm attempting to group a series of NSManagedObjects into sections. Every section would represent a period of 4 hours within a day.
- (NSString *)sectionIdentifier
{
// Create and cache the section identifier on demand.
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp)
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit) fromDate:[self created]];
tmp = [NSString stringWithFormat:@"%.0f %d %d %d", round(components.hour % 4), components.day, components.month, components.year];
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
In the above code, found in the NSManagedObject, the transient property sectionIdentifier
returns a string consisting of the period (of 4 hours) it is in, the day, month, and year of it's creation.
However, although the sort descriptor for the NSFetchedResultController's fetchRequest is set to sort the results in order of their creation date (newest objects at the bottom, oldest at the top), the fetch request is failing due to the section identifier not being ordered properly.
- (NSFetchedResultsController *) fetchedResultsController {
if (!_fetchedResultsController) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"PSSpace" inManagedObjectContext:self.managedObjectContext]];
[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"created" ascending:YES]]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"sectionIdentifier" cacheName:nil];
[_fetchedResultsController setDelegate:self];
}
return _fetchedResultsController;
}
CoreData: error: (NSFetchedResultsController) The fetched object at index 10 has an out of order section name '1 14 12 2013. Objects must be sorted by section name'
Please can you tell me how I can fix this issue with the ordering?
Thanks.
尝试类似
if (!tmp) {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit) fromDate:[self created]];
NSUInteger _y = (components.year * 1000000);
NSUInteger _m = (components.month * 10000);
NSUInteger _d = (components.day * 100);
NSUInteger _h = round(components.hour / 4);
NSUInteger token = (_y + _m + _d + _h);
tmp = [NSString stringWithFormat:@"%lu", token];
[self setPrimitiveSectionIdentifier:tmp];
}
链接地址: http://www.djcxy.com/p/36116.html