A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Micro 高级黑马   /  2015-2-14 22:26  /  636 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


  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.         [hide]
  29.         stu1.name = @"xiaojunquan";
  30.         NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,stu6, nil];
  31.         NSArray *array2 =[array sortedArrayUsingSelector:@selector(compareStuden:)];
  32.         NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
  33.         
  34.           NSLog(@" 以下为高级方法排序:");
  35.         sortStudent(array);[/hide]
  36.         
  37.         [stu5 release];
  38.         [stu4 release];
  39.         [stu3 release];
  40.         [stu2 release];
  41.         [stu1 release];
  42.       
  43.     }
  44.     return 0;
  45. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马