- #import <Foundation/Foundation.h>
- #import "Student.h"
- //对5个学生对象按照成绩—》年龄—》姓名优先级排序
- void sortStudent(NSArray *array){
- //1.按分数从大到小排序
- NSSortDescriptor *scoreDesc = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];
- //2.按年龄从大到小排序
- NSSortDescriptor *ageDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
- //3.按姓名从小到大排序
- NSSortDescriptor *nameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
- //4.按顺序填加描述器,用数组保存
- NSArray *desc = [NSArray arrayWithObjects:scoreDesc,ageDesc,nameDesc, nil];
- //5.让array 使用描述器来排序数组,因为nsarray是不可变的,所以存放在array2 中。
- NSArray *array2= [array sortedArrayUsingDescriptors:desc];
- //6.打印出排序结果
- NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
- }
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // insert code here...
- Student* stu1= [[Student alloc]initName:@"JJ" andAge:22 andScore:100];
- Student* stu2= [[Student alloc]initName:@"YY" andAge:20 andScore:90];
- Student* stu3= [[Student alloc]initName:@"ff" andAge:20 andScore:90 ];
- Student* stu4= [[Student alloc]initName:@"dd" andAge:24 andScore:77];
- Student* stu5= [[Student alloc]initName:@"bb" andAge:20 andScore:95];
-
- Student *stu6= [Student studentName:@"anzi" withAge:22 withScore:100 ];
- [hide]
- stu1.name = @"xiaojunquan";
- NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,stu6, nil];
- NSArray *array2 =[array sortedArrayUsingSelector:@selector(compareStuden:)];
- NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
-
- NSLog(@" 以下为高级方法排序:");
- sortStudent(array);[/hide]
-
- [stu5 release];
- [stu4 release];
- [stu3 release];
- [stu2 release];
- [stu1 release];
-
- }
- return 0;
- }
复制代码
|
|