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.
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.
Thanks in advance.
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
fetchedResultsControllermethod. To change the method in which the table sorts its items, simply use this: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 usetimeIntervalSinceReferenceDateto compare and sort each NSDate as tassinari said. I recommend you use an NSFetchedResultsController though.