黑马程序员技术交流社区

标题: 非高级方法对数组对象(包括非OC对象)的排序 [打印本页]

作者: Micro    时间: 2015-2-14 22:35
标题: 非高级方法对数组对象(包括非OC对象)的排序
本帖最后由 Micro 于 2015-2-14 22:45 编辑
  1. -(NSComparisonResult)compareStuden:(Student *)stu{
  2.     //将非OC对象包装成OC对象
  3.     NSNumber *score1 =[NSNumber numberWithInt:self.score];
  4.     NSNumber *score2 =[NSNumber numberWithInt:stu.score];
  5.     NSNumber *age1 = [NSNumber numberWithInt:self.age];
  6.     NSNumber *age2 = [NSNumber numberWithInt:stu.age];
  7.    
  8.     NSComparisonResult result= [score1 compare: score2];
  9.     if (result==NSOrderedSame) {
  10.         result = [age1 compare: age2];
  11.         if (result== NSOrderedSame) {
  12.             result =  [self.name compare:stu.name];
  13.         }
  14.     } return result;
  15. }

  16. -(NSString *)description{
  17.    // NSLog(@"My Name is @%,my age is i%,my score is i%",_name,_age,_score);
  18.    NSString *str= [NSString
  19. stringWithFormat:@"My Name is %@ ,my age is %i ,my score is %i" ,self.name, self.age, self.score];
  20.     return  str;
  21. }
  22. -(void)dealloc{
  23.     [_name release];
  24.     NSLog(@"姓名为%@的学生被回收了。。。。",_name);
  25.     [super dealloc];
  26.    
  27. }
复制代码
  1. int main(int argc, const char * argv[]) {
  2.     @autoreleasepool {
  3.         // insert code here...
  4.         Student* stu1= [[Student alloc]initName:@"JJ" andAge:22 andScore:100];
  5.         Student* stu2= [[Student alloc]initName:@"YY" andAge:20 andScore:90];
  6.         Student* stu3= [[Student alloc]initName:@"ff" andAge:20 andScore:90 ];
  7.         Student* stu4= [[Student alloc]initName:@"dd" andAge:24 andScore:77];
  8.         Student* stu5= [[Student alloc]initName:@"bb" andAge:20 andScore:95];
  9.         
  10.         Student *stu6= [Student studentName:@"anzi" withAge:22 withScore:100 ];
  11.         
  12.         stu1.name = @"xiaojunquan";
  13.         NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,stu6, nil];
  14.         NSArray *array2 =[array sortedArrayUsingSelector:@selector(compareStuden:)];
  15.         NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
  16.         
  17.           NSLog(@" 以下为高级方法排序:");
  18.         sortStudent(array);
  19.         
  20.         [stu5 release];
  21.         [stu4 release];
  22.         [stu3 release];
  23.         [stu2 release];
  24.         [stu1 release];
  25.       
  26.     }
  27.     return 0;
  28. }
复制代码








作者: 临汾皮皮    时间: 2015-2-14 22:38
很不错~~~




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