Search code examples
iosnsdatensfetchedresultscontrollernsfetchrequestnssortdescriptor

Multiple NSSortDescriptor Not Working When The 1st Descriptor is NSDate


I am trying to separate the data into sections by 'recordDate' then for each section the data will be sorted by 'elementName' in ascending order. Following is the current code (not working):

NSManagedObjectContext *context = self.tankDatabase.managedObjectContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Log"];
request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"recordDate" ascending:NO], [NSSortDescriptor sortDescriptorWithKey:@"elementName" ascending:YES selector:@selector(localizedStandardCompare:)], nil];
request.predicate = [NSPredicate predicateWithFormat:@"ownedBy = %@", self.tank];


self.controller = [[NSFetchedResultsController alloc]
                                          initWithFetchRequest:request
                                          managedObjectContext:context
                                          sectionNameKeyPath:@"recordDate"
                                          cacheName:nil];

self.controller.delegate = self;

NSError *error;
BOOL success = [self.controller performFetch:&error];

However when I tried to use other properties to sort (for example: elementName ASC, value DESC and group them by elementName) it does work as it should. Please note that the recordDate is a 'Date' type in data model and NSDate in the class.

Also the recordDate contains minute & seconds where it needs to be grouped to that detail.

I've tried to search the entire internet for similar case but I haven't found any solutions that work. What do I miss in my code? Or is it just an Apple bug? Thank you for your time and assistance.


Solution

  • I finally figured it out:

    Apparently it's the sub-seconds information that also being saved into Core Data making the comparison between dates (even though the dates being compared share the exact same date) not working.

    So what I did was to remove the sub-seconds information before saving it to Core Data:

    self.recordDate = [NSDate dateWithTimeIntervalSinceReferenceDate:floor([recordDate timeIntervalSinceReferenceDate])];
    

    I hope this can help anyone facing the same problem. Cheers!