Baub
Baub

Reputation: 5044

Sort UITableView (Core Data) via NSDate

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.

Upvotes: 4

Views: 1525

Answers (3)

Andrew R.
Andrew R.

Reputation: 943

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];
    ...
}

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.

Upvotes: 3

Dylan Reich
Dylan Reich

Reputation: 1430

This is what I do:

Add:

static NSDateFormatter *dateFormatter = nil;
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    }

to your cellForRowAtIndexPath method outside of the if (cell == nil) part. Then, where you are setting the information for your cells (EDIT: this is where your array gets sorted with the newest at the top):

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
        [myArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

Then, you can do whatever you want with the date. Example:

cell.textLabel.text = [dateFormatter stringFromDate:myObject.creationDate];

Upvotes: 1

tassinari
tassinari

Reputation: 2363

Use timeIntervalSinceReferenceDate or timeIntervalSince1970 on your NSDate, both return timeIntervals which are typedefed to doubles and sortable.

Upvotes: 1

Related Questions