黑马程序员技术交流社区

标题: OC数组排序,对学生对象排序 [打印本页]

作者: Micro    时间: 2015-2-14 22:26
标题: OC数组排序,对学生对象排序

  1. #import <Foundation/Foundation.h>
  2. #import "Student.h"
  3. //对5个学生对象按照成绩—》年龄—》姓名优先级排序
  4. void sortStudent(NSArray *array){
  5.     //1.按分数从大到小排序
  6.     NSSortDescriptor *scoreDesc = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];
  7.     //2.按年龄从大到小排序
  8.     NSSortDescriptor *ageDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
  9.     //3.按姓名从小到大排序
  10.     NSSortDescriptor *nameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
  11.     //4.按顺序填加描述器,用数组保存
  12.     NSArray *desc = [NSArray arrayWithObjects:scoreDesc,ageDesc,nameDesc, nil];
  13.     //5.让array 使用描述器来排序数组,因为nsarray是不可变的,所以存放在array2 中。
  14.     NSArray *array2= [array sortedArrayUsingDescriptors:desc];
  15.     //6.打印出排序结果
  16.     NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
  17. }

  18. int main(int argc, const char * argv[]) {
  19.     @autoreleasepool {
  20.         // insert code here...
  21.         Student* stu1= [[Student alloc]initName:@"JJ" andAge:22 andScore:100];
  22.         Student* stu2= [[Student alloc]initName:@"YY" andAge:20 andScore:90];
  23.         Student* stu3= [[Student alloc]initName:@"ff" andAge:20 andScore:90 ];
  24.         Student* stu4= [[Student alloc]initName:@"dd" andAge:24 andScore:77];
  25.         Student* stu5= [[Student alloc]initName:@"bb" andAge:20 andScore:95];
  26.         
  27.         Student *stu6= [Student studentName:@"anzi" withAge:22 withScore:100 ];
  28.         
  29.         
  30.         [stu5 release];
  31.         [stu4 release];
  32.         [stu3 release];
  33.         [stu2 release];
  34.         [stu1 release];
  35.       
  36.     }
  37.     return 0;
  38. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2