gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:12:24 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com