NSSortDescriptor should sort NSDates

achi picture achi · Aug 27, 2012 · Viewed 10.9k times · Source

It appears NSSortDescriptor should be a fairly easy class to work with.

I have stored in CoreData an entity with an attribute of type NSDate appropriately named @"date". I am attempting to apply a sort descriptor to a NSFetchRequest and it doesn't appear to be returning the results I had hoped for.

The result I am hoping for is to simply arrange the dates in chronological order, and instead they are returned in the order for which they were added to CoreData.

Perhaps you can offer guidance?

Is the parameter 'ascending' what controls the sort?

Some Code:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entityDesc];

[fetchRequest setFetchBatchSize:10];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];    

[fetchRequest setSortDescriptors:sortDescriptors];

NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

Answer

Jaybit picture Jaybit · Aug 27, 2012

Here is more information on NSSortDescriptors

Or if you want to sort an array of dates after getting them for coreDate:

//This is how I sort an array of dates.
NSArray *sortedDateArray = [dateArray sortedArrayUsingFunction:dateSort context:NULL];

// This is a sorting function
int dateSort(id date1, id date2, void *context)
{    
    return [date1 compare:date2];
}

Here is code straight from apple for sorting integers (just modify to sort dates):NSComparator

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];