简体   繁体   中英

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?

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM