Objective-C 排序,objective-c排序
在Objective-C中,排序分為:
1、Foundation架構中的對象排序
2、自訂對象排序
例子:每個學生都有一個成績score屬性,根據成績score對學生排序
自訂對象 Student.h
#import <Foundation/Foundation.h>#import "Student.h"int main(int argc, const char * argv[]) { @autoreleasepool { //1、Foundation架構中的對象排序 NSArray *arr = @[@12, @25, @15, @7, @18]; NSLog(@"排序前: %@", arr); // 注意: 想使用compare方法對數組中的元素進行排序, 那麼數組中的元素必須是Foundation架構中的對象, 也就是說不能是自訂對象 NSArray *newArr = [arr sortedArrayUsingSelector:@selector(compare:)]; NSLog(@"排序後: %@", newArr); //2、自訂對象排序 Student *stu1 = [Student new]; stu1.score = 91; Student *stu2 = [Student new]; stu2.score = 97; Student *stu3 = [Student new]; stu3.score = 95; Student *stu4 = [Student new]; stu4.score = 87; NSArray *studentArr = @[stu1, stu2, stu3, stu4]; NSLog(@"排序前: %@", studentArr); // 按照學生的成績進行排序 // 不能使用compare:方法對自訂對象進行排序 // NSArray *newArr = [arr sortedArrayUsingSelector:@selector(compare:)]; // 該方法預設會按照升序排序 NSArray *newStudentArr = [studentArr sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(Student *obj1, Student *obj2) { //升序 return obj1.score > obj2.score; //降序// return obj1.score < obj2.score; }]; NSLog(@"成績排序後: %@", newStudentArr); return 0; } return 0;}
結果: