日期为 sectionNameKeyPath 的 NSFetchedResultsController [英] A NSFetchedResultsController with date as sectionNameKeyPath
问题描述
我开发了一个使用 Core Data 的应用程序.在一个 UITableView 中,我想显示我的实体列表,按对象的保存日期排序.当我这样做时:
I develop an application which uses Core Data. In one UITableView, I want to display a list of my entities, sorted by the saved date of the objects. When I do this:
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"date"
cacheName:nil];
我为每个对象获得了一个新部分,因为此代码也根据秒对日期进行分组.但我想要一个按日期分组的对象列表,但只能按日、月和年分组.是否可能以及如何实现?
I get for each object a new section because this code groups the dates according to the seconds, too. But I want a list of the objects, grouped by date, but only according to the day, month and year. Is it possible and how?
非常感谢您的帮助!!;)
Thank you very much for your help!! ;)
推荐答案
这应该对你有用:
- (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;
}
Jus 看到了您的评论以及您想要实现的目标,您可以创建一个瞬态 NSDate
属性(非持久性),其格式与上述代码类似(即没有 H:mm:ss ZZZZ) 并将该属性用作您的 sectionNameKeyPath
值.
Jus saw your comment and for what you are trying to achieve, you could create a transient NSDate
attribute (non persistent) that is formatted in a similar way to the above code (i.e. without H:mm:ss ZZZZ) and use that attribute as your sectionNameKeyPath
value.
简而言之,对于 foo
对象,具有 fooDate
和 fooDateTransient
属性,您将:
So in a nutshell for a foo
object, with fooDate
and fooDateTransient
attributes, you would:
获取您的
foo.fooDate
属性
使用上面的代码(或类似代码)对其进行转换,并将 NSDate
结果分配给 foo.fooDateTransient
Transform it using the code above (or similar) and assign the NSDate
result to foo.fooDateTransient
在创建 fetchedResultsController
对象时,使用 fooDateTransient
作为您的 sectionNameKeyPath
.
Use fooDateTransient
as your sectionNameKeyPath
when creating the fetchedResultsController
object.
PS:我自己还没有测试过,但应该值得一试!
PS: I haven't tested this myself but should be worth a shot!
祝你好运罗格
这篇关于日期为 sectionNameKeyPath 的 NSFetchedResultsController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!