ios - 如何对包含日期对象的自定义数组进行排序

标签 ios objective-c nsdate nspredicate nssortdescriptor

我有一个 NSArray,它包含这样的自定义对象:

NSArray *array = {
 students,students

}

Student 对象依次存储如下值:

student.name,
student.class,
student.admissionDate
student.school ..etc

现在我想要一个 NSArray,其中包含所有根据 admissionDate 排序的学生详细信息。

我尝试使用 NSSortDecriptor 但它对我没有帮助。

编辑

经过一番努力,我成功地形成了一个 NSDictionary 的 NSMutable 数组,它看起来像:

      for(Student *arr in array)
{

     NSMutableDictionary *dict;
    dict = [[NSMutableDictionary alloc]init];
    [dict setObject:arr.stuName forKey:@"name"];
    [dict setObject:arr.stuAdate forKey:@"date"];
    [dict setObject:arr.stuClass    forKey:@"class"];

    [expenseArray addObject:dict];
}



Printing description of expenseArray:
<__NSArrayM 0x7fe703833f70>(
{
 name = uuu;
 Adate = "2015-10-10 10:56:03 +0000";
 class = 1st;
},
{
  name = abc;
   Adate = "2015-10-07 11:10:00 +0000";
  class = 3rd;
},
 {
   name = btw;
   Adate = "2015-10-10 11:13:47 +0000";
   class = 4th;
 }
  )

现在我如何根据日期排序

最佳答案

排序描述符应该适合你

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"admissionDate" ascending:YES];
NSArray *sortedStudents = [studentArray sortedArrayUsingDescriptors:@[sortDescriptor]];

下面是工作示例

NSMutableArray *studentArray = [NSMutableArray new];

for (int i = 0; i < 8; i++) {
    Student *student = [Student new];

    unsigned int randomInterval = arc4random();
    student.admissionDate = [NSDate dateWithTimeIntervalSinceNow:randomInterval];
    [studentArray addObject:student];
}


for (Student *student in studentArray) {
    NSLog(@"%@", student.admissionDate);
}


NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"admissionDate" ascending:YES];
NSArray *sortedStudents = [studentArray sortedArrayUsingDescriptors:@[sortDescriptor]];

NSLog(@"\n\n * * * * * After Sorting * * * * * *\n\n");

for (Student *student in sortedStudents) {
    NSLog(@"%@", student.admissionDate);
}

日志

2024-02-11 23:47:47 +0000
2093-11-13 21:49:48 +0000
2042-04-06 23:53:28 +0000
2032-12-23 01:49:46 +0000
2102-12-28 23:08:06 +0000
2058-10-17 14:14:27 +0000
2142-02-01 07:19:34 +0000
2048-05-14 07:07:04 +0000

* * * * * After Sorting * * * * * *

2024-02-11 23:47:47 +0000
2032-12-23 01:49:46 +0000
2042-04-06 23:53:28 +0000
2048-05-14 07:07:04 +0000
2058-10-17 14:14:27 +0000
2093-11-13 21:49:48 +0000
2102-12-28 23:08:06 +0000
2142-02-01 07:19:34 +0000

关于ios - 如何对包含日期对象的自定义数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053471/

相关文章:

objective-c - iOS 应用程序使用 Windows Azure 服务管理 API 的可行性?

ios - 创建垂直 TableView 的水平列表

ios - 如何在 swift 中使用带有组件的 NSDate 来获取正确的时间

iOS GCD : Difference between any global queue and the one with background priority (DISPATCH_QUEUE_PRIORITY_BACKGROUND)?

iphone - iOS - 删除存储在主 NSDictionary 中的所有 NSDictionaries 上包含键的所有条目

ios - 知道数字的最高位数

ios - 是否可以在不使用日历组件的情况下比较NSDate对象?

ios - 如何写一个软件同步文件到ipad

objective-c - NSRangeException 困惑

iphone - 日期时间到 NSDate