NSFetchedResultsController组每4小时进入一个部分

时间:2013-12-15 20:57:09

标签: core-data uitableview nsfetchedresultscontroller nsfetchrequest

我正在尝试将一系列NSManagedObjects分组。每个部分在一天内代表4小时。

- (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;
}

在上面的代码中,在NSManagedObject中找到,瞬态属性sectionIdentifier返回一个字符串,该字符串包含它所在的句点(4小时),创建日期,月份和年份。

但是,虽然NSFetchedResultController的fetchRequest的排序描述符设置为按照创建日期的顺序对结果进行排序(最新的对象位于底部,最旧的位于顶部),但由于节标识符不是,因此获取请求失败订购得当。

- (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)索引10处的获取对象具有无序部分名称“1 14 12 2013.对象必须按部分名称排序”

请告诉我如何通过订购解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

尝试类似

的内容
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];
}