12

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?

ASHISHT
  • 305
  • 1
  • 14
android iPhone
  • 860
  • 2
  • 11
  • 22
  • 3
    You need to remove the time from the date. http://stackoverflow.com/questions/4187478/truncate-nsdate-objective-c – Lou Franco Feb 07 '12 at 20:00
  • do you need the time information for anything else? If not you could set the time components to 0 when setting the time of the core data object. If you need it you have to add another attribute which uses either NSDate without time components or a yyyymmdd string. – Matthias Bauch Feb 07 '12 at 20:02

2 Answers2

6

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];
John Fontaine
  • 1,019
  • 9
  • 14
0

CoreData supports NSDate, but it will always include the hour. The only thing that I can think of is to have a custom, readonly property that has a timestamp without hours included and then create sort descriptor for that property.

Eimantas
  • 48,927
  • 17
  • 132
  • 168