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?
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With