Sort NSFetchRequest by date and then by alphabetical order

android iPhone picture android iPhone · Feb 7, 2012 · Viewed 8.2k times · Source

I want to order a NSFetchRequest first by date and then, if it matches the same day order by name. I use a UIDatePicker to get the date and the save it using Core Data

[self.managedObject setValue:self.datePicker.date forKey:self.keypath];

and sort the NSFetchRequest like this:

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"day" ascending:NO];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

Now my problem is that it only be ordered by date and not by name because the UIDatePicker stored in Core Data the date but also the hour. So even if the same day, not sorted by "name" in that same day because the hour is different. So how do I save in core data only the date mm/dd/yyyy and not de hour from a UIDatePicker?

Or do you think of any other solution?

Answer

John Fontaine picture John Fontaine · Jul 8, 2015

Use a comparator block for your date sort to convert the date to a string with format yyyyMMdd.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMdd"];
NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO comparator:^NSComparisonResult(NSDate *obj1, NSDate *obj2) {
    return [[formatter stringFromDate:obj1] compare:[formatter stringFromDate:obj2]];
}];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];