Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSFetchRequest by date and then by alphabetical order

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?

like image 240
android iPhone Avatar asked Feb 07 '12 19:02

android iPhone


1 Answers

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];
like image 93
John Fontaine Avatar answered Oct 17 '22 05:10

John Fontaine