数组排序方法

2017-08-16  本文已影响11人  PZcoder

数组排序方法介绍 (注意:排序后返回值是不可变数组类型)

//排序方法1 (块排序)

    NSArray * arr4 = @[@"aaa",@"ccc",@"ddd",@"bbb"];
    NSArray * newarr4 = [arr4 sortedArrayUsingComparator:^NSComparisonResult(NSString * obj1, NSString * obj2)
                         {
                             NSString * str1 = (NSString *)obj1;
                             NSString * str2 = (NSString *)obj2;

                             if ([str1 compare:str2] == NSOrderedDescending)
                             {
                                 return NSOrderedDescending;
                             }
                             else if ([str1 compare:str2])
                             {
                                 return NSOrderedAscending;
                             }else
                                 return NSOrderedSame;
                             
                             return  [obj1 compare:obj2];
                         }];

//打印排序后的数组
    NSLog(@"%@",newarr4);
    

//排序方法2.

//创建对象,并给相应对象的属性赋值
    Student * stu = [Student new];
    stu.name = @"唐僧";
    stu.age = 23;
    Student * stu1 = [Student new];
    stu1.name = @"孙悟空";
    stu1.age = 1500;
    Student * stu2 = [Student new];
    stu2.name = @"猪八戒";
    stu2.age = 1800;
    Student * stu3 = [Student new];
    stu3.name = @"沙和尚";
    stu3.age = 32;
    
//把对象添加到数组中
    NSArray * team = @[stu,stu1,stu2,stu3];

//按年龄降序排列
    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];

//按名字升序排列
    NSSortDescriptor * sort1 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];

    team =  [team sortedArrayUsingDescriptors:@[sort1,sort]];//sort1 优先,sort 其次。
    
//打印排序后数组
    for (int i = 0; i < team.count; i++)
    {
        NSLog(@"%@",team[i]);
    }
    

//排序方法3 (使用自定义的排序方法排序)

    NSArray * team = @[stu,stu1,stu2,stu3];
    
  //使用自定义的比较方法进行排序
    team =  [team sortedArrayUsingSelector:@selector(myCompare:)];
    
    for (int i = 0; i<team.count; i++)
    {
        NSLog(@"%@",team[i]);
    }
    
    //比较方法实现(注意返回值类型,此方法也可实现在其他类中,只需头文件引入即可)
    -(NSComparisonResult)myCompare:(Student *)other
    {
        return -1 * (self.age - other.age);
    }
上一篇下一篇

猜你喜欢

热点阅读