Objective-C 排序,objective-c排序

來源:互聯網
上載者:User

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;}

 結果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.