- void arraySort() {
- Student *stu1 = [[Student alloc] initWithName:@"lisi" andAge:18 andScore:87];
- Student *stu2 = [[Student alloc] initWithName:@"wangwu" andAge:19 andScore:60];
- Student *stu3 = [[Student alloc] initWithName:@"zhangsan" andAge:28 andScore:89.5];
- Student *stu4 = [[Student alloc] initWithName:@"zhaoliu" andAge:38 andScore:99];
- Student *stu5 = [[Student alloc] initWithName:@"liMing" andAge:17 andScore:79];
-
- NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4,stu5, nil];
- NSLog(@"未排序前--------------------------------------\n");
- [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
- NSLog(@"%@",obj);
- }];
-
- // 1.先按照成绩进行排序
- // 这里的key写的是get的名称
- NSSortDescriptor *scoreDesc = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES];
- // 2.再按照年龄进行排序
- NSSortDescriptor *ageDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
- // 3.再按照姓名进行排序
- NSSortDescriptor *nameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
- // 按顺序添加排序描述器
- NSArray *descs = [NSArray arrayWithObjects:scoreDesc, ageDesc, nameDesc, nil];
-
- NSArray *array2 = [array sortedArrayUsingDescriptors:descs];// 按升序排列
- NSLog(@"排序后--------------------------------------");
- [array2 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
- NSLog(@"%@",obj);
- }];
-
-
- }
复制代码 |