1. 程式人生 > >【iOS】物件陣列排序最簡單的方法

【iOS】物件陣列排序最簡單的方法

一個數組內是物件型別.想根據物件內的屬性進行排序.
很多人第一想到的是利用謂詞.其實陣列自帶了一個更簡便的方法便於我們進行排序

- (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);

“`