Reputation: 1024
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.
Upvotes: 0
Views: 1038
Reputation: 52
Yes, if you want your subsorting descriptor (based on elementName) to kick in, then you need some ties with respect to recordDate, so your idea of truncating recordDate is good. In fact, many a time, NSDate information is truncated to YY:MM:DD so all events belonging to the same day are indistinguishable.
As an aside, often only your sectionNameKeyPath needs to be "coarse grained", e.g., you make a new transient attribute by removing the subsecond information from recordDate, and feed THAT to NSFetchedResultsController as sectionNameKeyPath. In other words, you can continue with recordDate as it is...
This would be similar to Last Name sorting (Ascending, say) where the section names are A, B, C, ..., Z.
Upvotes: 0
Reputation: 1024
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!
Upvotes: 1