问题描述
- iphone在数组中排序日期
- SQLite数据库中有下面的数组:
({ id=1;duedate = ""01-Apr-2013"";}{ id=2;duedate = ""01-May-2013"";}{id=3;duedate = ""01-Jun-2013"";}{ id=4;duedate = ""11-Jul-2013"";})
排序的代码:
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@""duedate"" ascending:YES];[assessment_list sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
但是最后出现的排序不对:
({ id=1;duedate = ""01-Apr-2013"";}{id=3;duedate = ""01-Jun-2013"";}{id=2;duedate = ""01-May-2013"";}{ id=4;duedate = ""11-Jul-2013"";})
不知道为什么?
解决方案
因为它是按照字母顺序排列的
想根据日期排序,用下面的方法:
NSInteger dateSort(id dict1 id dict2 void* context){NSDateFormatter *formatter = [[NSDateFormatter alloc] init];[formatter setDateFormat:@""mm/dd/yyyy""];NSDate *date1 = [formatter dateFromString:[dict1 objectForKey:@""duedate""]];NSDate *date2 = [formatter dateFromString:[dict2 objectForKey:@""duedate""]]; return [[date1 compare:date2];}
调用函数:
[dateArray sortUsingFunction:dateSort context:NULL];
时间: 2025-01-11 11:22:38