iOS开发经验收集ios

【IOS】对象数组排序最简单的方式

2017-05-31  本文已影响113人  雨影

一个数组内是对象类型.想根据对象内的属性进行排序.
很多人第一想到的是利用谓词.其实数组自带了一个更简便的方法便于我们进行排序

- (void)sortUsingComparator:(NSComparator NS_NOESCAPE)cmptr NS_AVAILABLE(10_6, 4_0);

举例.
定义一个 Person 对象

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property(nonatomic,readwrite)int weight;
@end

使用方法

    Person *person1 =[[Person alloc]init];
    Person *person2 =[[Person alloc]init];
    Person *person3 =[[Person alloc]init];
    
    person1.weight =1;
    NSMutableArray *array =[[NSMutableArray alloc]init];
    [array addObject:person1];
    person2.weight =3;
    [array addObject:person2];
    person3.weight =2;
    [array addObject:person3];
    for (Person *p in array) {
         NSLog(@"排序前%d",p.weight);
    }
   
    [array sortUsingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
        return [@(obj1.weight) compare:@(obj2.weight)];
    }];
    for (Person *p in array) {
        NSLog(@"排序后%d",p.weight);
    }

打印日志为:

2017-05-27 17:20:51.382 Demo[18726:662926] 排序前1
2017-05-27 17:20:51.383 Demo[18726:662926] 排序前3
2017-05-27 17:20:51.383 Demo[18726:662926] 排序前2

2017-05-27 17:20:51.383 Demo[18726:662926] 排序后1
2017-05-27 17:20:51.383 Demo[18726:662926] 排序后2
2017-05-27 17:20:51.383 Demo[18726:662926] 排序后3

是不是感觉很方便?所以多看看系统定义的方法对我们提高效率非常有用

另外分享一些常用 OC 排序方法:
1).不可变数组

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator;
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;

2)可变数组

- (void)sortUsingSelector:(SEL)comparator;
- (void)sortUsingComparator:(NSComparator)cmptr;

3).字典排序

- (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr 
- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator;

1).不可变数组排序:(方法1)

NSArray *arr = @[@"aa",@"rr",@"pp",@"hh",@"xx",@"vv"];
   //用系统的方法进行排序,系统缺少两个元素比较的方法.
   //selector方法选择器. 
   
    NSArray *sortArr = [arr sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"%@",sortArr);
   

方法2:block块语法

   [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2];
    }];
     NSLog(@"%@",arr);
    }

2).可变数组排序:方法1

    NSMutableArray *arr = [@[@54 ,@33,@12,@23,@65] mutableCopy];
    [arr sortUsingSelector:@selector(compare:)];//compare数组中两个元素比较的方法
    NSLog(@"%@",arr);
方法2
   [arr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSNumber *)obj1 compare:(NSNumber *)obj2];
    }];
     NSLog(@"%@",arr);
    }

注:字典方法类似

例题:定义一个学生对象,对学生对象按照,姓名,年龄,成绩,学号进行排序,(两种排序方式)

方法1:(用selector方法选择器,需要重新定义comparator)

代码如下:

1.对象声明(student.h中)

@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) CGFloat score;
@property (nonatomic, assign) NSInteger number;

//初始化
- (id)initWithName:(NSString *)name age:(NSInteger)age score:
                                  (CGFloat)score number:(NSInteger)number;
//便利构造器
+ (id)studentWithName:(NSString *)name age:(NSInteger)age score:
                                   (CGFloat)score number:(NSInteger)number;
//两个学生按照年龄比较的方法
- (NSComparisonResult)compareByAge:(Student *)stu;

//两个学生按照姓名比较的方法
- (NSComparisonResult)compareByName:(Student *)stu;

//两个学生按照成绩比较的方法
- (NSComparisonResult)compareByScore:(Student *)stu;

//两个学生按照学号比较的方法
- (NSComparisonResult)compareByNumber:(Student *)stu;

2.实现(student.m文件)
 - (id)initWithName:(NSString *)name age:(NSInteger)age score:
                                        (CGFloat)score number:(NSInteger)number {

     self = [super init];
     if (self != nil) {
         self.name = name;
         self.age = age;
         self.score = score;
         self.number = number;
     }
     return self;
}
//便利构造器
+ (id)studentWithName:(NSString *)name age:(NSInteger)age score:
                                       (CGFloat)score number:(NSInteger)number {

    Student *student = [[Student alloc] initWithName:name
                                       age:age score:score number:number];
 
     return student;
}
//重写description
- (NSString *)description {
    return [NSString stringWithFormat:
                   @"name:%@,age:%ld,socre:%.1f,number:%ld",
                                  self.name, self.age, self.score, self.number];
}


//两个学生按照年龄比较的方法
- (NSComparisonResult)compareByAge:(Student *)stu {

    return [@(self.age) compare:@(stu.age)];//或者下面方法
    //return self.age > stu.age ? NSOrderedDescending
                    : self.age == stu.age ? NSOrderedSame : NSOrderedAscending;
}

//两个学生按照姓名降序的方法
- (NSComparisonResult)compareByName:(Student *)stu {
    return - [self.name compare:stu.name];
}

//两个学生按照成绩降序比较的方法
- (NSComparisonResult)compareByScore:(Student *)stu {
return -[@(self.score) compare: (stu.score)];
    //return self.score < stu.score ? NSOrderedDescending :
                   self.score == stu.score ? NSOrderedSame : NSOrderedAscending;
     
}
 
//两个学生按照学号升序的方法
- (NSComparisonResult)compareByNumber:(Student *)stu {
 
      return [@(self.number) compare: (stu.number)];
     //return self.number > stu.number ? NSOrderedDescending 
              : self.number == stu.number ? NSOrderedSame : NSOrderedAscending;
}

主函数(main.h)

Student *student1 = [Student studentWithName:@"a" age:23 score:21 number:3434343];
Student *student2 = [Student studentWithName:@"b" age:45 score:432.4 number:324];
Student *student3 = [Student studentWithName:@"c" age:32 score:4321.4 number:2343];
Student *student4 = [Student studentWithName:@"d" age:7 score:43.4 number:233];
Student *student5 = [Student studentWithName:@"e" age:73 score:65 number:2332424];
        
NSMutableArray *arr = [NSMutableArray arrayWithObjects:
                           student1,student2,student3,student4,student5,nil];
      
        
  //按照年龄升序排序
  [arr sortUsingSelector:@selector(compareByAge:)];
  NSLog(@"%@",arr);
  //按照成绩降序排序
  [arr sortUsingSelector:@selector(compareByScore:)];
  NSLog(@"%@",arr);
  //按照姓名降序排序
  [arr sortUsingSelector:@selector(compareByName:)];
  NSLog(@"%@",arr);
  //按照学号升序排序
  [arr sortUsingSelector:@selector(compareByNumber:)];

 NSLog(@"%@",arr);

方法2.用block块语法进行排序

       //按年龄升序排序
        [arr sortUsingComparator:^(id obj1,id obj2) {
          return [@(((Student *)obj1).age) compare: @(((Student *)obj2).age)];
        }];
        NSLog(@"%@",arr);
        
        //按成绩降序排序
        [arr sortUsingComparator:^(id obj1,id obj2) {
           return [@(((Student *)obj1).score) compare: @(((Student *)obj2).score)];
        }];
        
        NSLog(@"%@",arr);
        //按姓名降序排序
        [arr sortUsingComparator:^(id obj1,id obj2) {
            return -[[(Student *)obj2 name] compare: [(Student *)obj1 name]];
        }];
        NSLog(@"%@",arr);
  //按学号升序排序
        NSComparator sortBlock = ^(id obj1,id obj2) {
           return [@(((Student *)obj1).number) compare: @(((Student *)obj2).number)];
        };
        [arr sortUsingComparator:sortBlock];
        NSLog(@"%@",arr);

上一篇下一篇

猜你喜欢

热点阅读