Search code examples
objective-csortingcore-datansfetchrequestnssortdescriptor

NSSortDescriptor should sort NSDates


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

Solution

  • Separate sort routines (functions or blocks) look like overkill to me. I am routinely sorting Core Data entities by date attribtues just with the sort descriptor method you show in your code. It works perfectly every time.

    Clearly, there must be some other mistake.

    • Check if the type is set correcly in your managed object model editor, and in the class file (Data.h, in your case).
    • Also, check if you are not manipulating this attribute so that the creation order ensues.
    • Also, make sure you are not mixing up this attribute with another attribute of type NSDate.