biz*_*z84 16 sql core-data uitableview ios
有没有办法按日期对CoreData实体中的对象进行分组,并使用它们在UITableView控件上创建多个部分?
本质上,我需要一些等同于以下伪SQL的东西,其中my_group_criteria()按天分组所有测试:
SELECT * FROM tests GROUP BY my_group_criteria(date)
Run Code Online (Sandbox Code Playgroud)
例如,查询会将以下行分为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]
Run Code Online (Sandbox Code Playgroud)
正如2中已经回答的那样,NSPredicate不适用于对实体进行分组,因此这可能不是最佳选择.
鉴于此,我如何根据类似于SQL GROUP BY的标准在UITableView中创建多个部分?
我想尽可能避免直接访问SQL-lite数据库.
相关问题1: NSPredicate:按NSDate属性的日期过滤对象
相关问题2: NSPredicate等同于SQL的GROUP BY
Mar*_*n R 13
您可以根据需要从Apple Developer Library 修改DateSectionTitles示例项目.
首先,您必须修改transient sectionIdentifier属性的访问器函数,以基于年+月+日(而不是仅年+月)创建节标识符:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
其次,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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7280 次 |
| 最近记录: |