Pau*_*tin 22 sorting iphone core-data nsfetchedresultscontroller
我开发了一个使用Core Data的应用程序.在一个UITableView中,我想显示我的实体列表,按照对象的保存日期排序.当我这样做:
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"date"
cacheName:nil];
Run Code Online (Sandbox Code Playgroud)
我为每个对象添加了一个新部分,因为此代码也根据秒数对日期进行分组.但我想要一个按日期分组的对象列表,但只根据日,月和年.有可能吗?怎么样?
非常感谢您的帮助!!;)
Rog*_*Rog 41
这应该是你的诀窍:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
Jus看到了你的评论以及你想要实现的目标,你可以创建一个瞬态NSDate属性(非持久性),其格式与上面的代码类似(即没有H:mm:ss ZZZZ)并使用该属性作为你的sectionNameKeyPath值.
因此,在一个简而言之foo对象,具有fooDate和fooDateTransient属性,你会:
获取您的foo.fooDate属性
使用上面的代码(或类似代码)对其进行转换,并将NSDate结果分配给foo.fooDateTransient
使用fooDateTransient为您sectionNameKeyPath创建时fetchedResultsController的对象.
PS:我自己没有测试过,但值得一试!
祝你好运,罗格
Mic*_*ord 23
查看:http://developer.apple.com/library/ios/#samplecode/DateSectionTitles/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009939
它适用于月份和年份,但它很容易使它适用于日,月和年.