我开发了一个使用 Core Data 的应用程序。在一个 UITableView 中,我想显示我的实体列表,按对象的保存日期排序。当我这样做时:
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"date"
cacheName:nil];
我为每个对象获得一个新部分,因为此代码也根据秒对日期进行分组。但我想要一个按日期分组的对象列表,但仅根据日、月和年分组。这可能吗?如何实现?
非常感谢您的帮助!! ;)
这应该可以为你解决问题:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *rawDateStr = [[[self.fetchedResultsController sections] objectAtIndex:section] name];
// Convert rawDateStr string to NSDate...
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"];
NSDate *date = [formatter dateFromString:rawDateStr];
// Convert NSDate to format we want...
[formatter setDateFormat:@"d MMMM yyyy"];
NSString *formattedDateStr = [formatter stringFromDate:date];
return formattedDateStr;
}
[EDIT]
只是看到了您的评论,对于您想要实现的目标,您可以创建一个瞬态NSDate
属性(非持久),其格式与上述代码类似(即没有 H:mm:ss ZZZZ),并使用该属性作为您的sectionNameKeyPath
value.
简而言之foo
对象,与fooDate
and fooDateTransient
属性,你会:
拿你的foo.fooDate
属性
使用上面的代码(或类似的)对其进行转换并分配NSDate
结果到foo.fooDateTransient
Use fooDateTransient
身为你的sectionNameKeyPath
创建时fetchedResultsController
object.
PS:我自己还没有测试过,但应该值得一试!
祝你好运,
罗格
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)