微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用NSPredicate在NSDate中按天分组-创建多个UITableView节所需

如何解决如何使用NSPredicate在NSDate中按天分组-创建多个UITableView节所需

您可以根据需要从Apple Developer Library修改DateSectionTitles示例项目。

首先,您必须修改transientsectionIdentifier属性的访问器功能,以基于年+月+日(而不是仅年+月)创建节标识符:

- (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 * 10000 + month * 100 + day);
         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 | NSDayCalendarUnit)
                               fromDate:[self timeStamp]];
        tmp = [Nsstring stringWithFormat:@"%d", [components year] * 10000 + [components month] * 100  + [components day]];
        [self setPrimitiveSectionIdentifier:tmp];
    }
    return tmp;
}

其次,titleForHeaderInSection必须更改委托方法,但是思想是相同的:从节标识符中提取年,月和日,并从中创建标题标题字符串:

- (Nsstring *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    id <NSFetchedResultsSectionInfo> theSection = [[fetchedResultsController sections] objectAtIndex:section];

    NSInteger numericSection = [[theSection name] integerValue];
    NSInteger year = numericSection / 10000;
    NSInteger month = (numericSection / 100) % 100;
    NSInteger day = numericSection % 100;

    // Create header title YYYY-MM-DD (as an example):
    Nsstring *titleString = [Nsstring stringWithFormat:@"%d-%d-%d", year, month, day];
    return titleString;
}

解决方法

也可以看看

核心数据按日期与FetchedResultsController一起分为几部分

有没有一种方法可以按日期对CoreData实体中的对象进行分组,并使用它们在UITableView控件上创建多个部分?

本质上,我需要等效于以下伪SQL的东西,其中my_group_criteria()按天对所有测试进行分组:

SELECT * FROM tests GROUP BY my_group_criteria(date)

例如,查询会将以下行分为3个单独的部分:

[test1 | 2013-03-18 15.30.22]
[test2 | 2013-03-18 14.30.22]
[test3 | 2013-03-18 13.30.22]

[test4 | 2013-03-17 18.30.22]
[test5 | 2013-03-17 19.30.22]

[test6 | 2013-03-15 20.30.22]

正如在2中已经回答的那样,NSPredicate不适用于对实体进行分组,因此这可能不是解决之道。

鉴于此,我如何基于类似于SQL GROUP BY的某些条件在UITableView中创建多个节?

我想尽可能避免直接访问SQL-lite数据库。

相关问题1:
NSPredicate:按NSDate属性的天筛选对象

相关问题2: NSPredicate等同于SQL的GROUP
BY

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。