通过NSDate对UITableView(核心数据)进行排序 [英] Sort UITableView (Core Data) via NSDate
问题描述
就本例而言,假设我有一个按钮,每次按下该按钮时,会将NSDate
添加到Core Data实体中.我还有一个TableView
,显示该实体的所有成员.
For the sake of this example, let's say I have a button that every time I press it adds a NSDate
into a Core Data entity. I also have a TableView
that displays all of the members of that entity.
如何按NSDate
对此TableView
排序?即将出现的格式如下:2011-08-09 21:52:13 +0000
,我想将最新的格式排在TableView
的顶部.
How can I sort this TableView
by NSDate
? The format that is coming out is as follows: 2011-08-09 21:52:13 +0000
and I want to sort with the most recent at the top of the TableView
.
谢谢.
推荐答案
如果您使用的是NSFetchedResultsController(如果将UI数据与UITableViewController一起使用,则应该如此),那么实际上已为您提供了这样做的代码. .假设您将默认的Core Data模板与UITableViewController一起使用,则应使用fetchedResultsController
方法.要更改表格对项目进行排序的方法,只需使用以下方法:
If you are using an NSFetchedResultsController (as you should be if you are using Core Data with a UITableViewController), then the code to do so is essentially provided for you. Assuming you use the default Core Data template with a UITableViewController, you should be provided with a fetchedResultsController
method. To change the method in which the table sorts its items, simply use this:
- (NSFetchedResultsController *)fetchedResultsController
{
...
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
...
}
应将@"Date"
替换为您将核心数据条目命名为存储日期的任何内容.如果您使用的是NSFetchedResultsController,则此排序应完全符合您的期望,并且是执行此操作的适当"方法.但是,如果不是,则必须使用timeIntervalSinceReferenceDate
来按照tassinari所说对每个NSDate进行比较和排序.我建议您尽管使用NSFetchedResultsController.
Where @"Date"
should be replaced with whatever you have named your Core Data entry storing the date as. This should sort exactly as you want it to and is the "appropriate" way to do it if you are using NSFetchedResultsController. If you are not, however, you will have to use timeIntervalSinceReferenceDate
to compare and sort each NSDate as tassinari said. I recommend you use an NSFetchedResultsController though.
这篇关于通过NSDate对UITableView(核心数据)进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!