我正在使用核心数据存储警报详细信息(AlarmDate存储为日期类型),同时获取我使用NSSortDescripotor的所有警报
NSManagedObjectContext *managedObjectContext = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Alarm"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"AlarmDate"
ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSArray *arrayForAllAlarms = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
对于上面它按照排序顺序返回警报,但我需要它还应该在排序时考虑AM和PM
示例:
如果添加警报日期,例如: 晚上11点 上午01:30和 晚上10点
它应该返回: 凌晨01:30 晚上10点和 晚上11点
谢谢!
答案 0 :(得分:0)
查找解决方案,为现有的已获取数组编写自定义排序,如下所示:
NSArray *arrayForAllAlarmsSorted = [arrayForAllAlarms sortedArrayUsingComparator:
^(Alarm *alarmObject1, Alarm *alarmObject2) {
NSDate *dateForAlarm1 = [NSDate date:alarmObject1.alarmDateTime withFormat:@"hh:mm a"];
NSDate *dateForAlarm2 = [NSDate date:alarmObject2.alarmDateTime withFormat:@"hh:mm a"];
return [dateForAlarm1 compare:dateForAlarm2];
}];
NSDate类别函数写为:
+(NSDate *)date:(NSDate *)date withFormat:(NSString *)format {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
dateFormatter.dateFormat = format;
NSDate *newDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:date]];
return newDate;
}