NSSortDescriptor對象進行數組排序,js對象數組排序

來源:互聯網
上載者:User

NSSortDescriptor對象進行數組排序,js對象數組排序

//建立一個數組

    NSArray *array = @[@"zhangsan", @"lisi", @"zhonger", @"zhubada", @"honghunag"];

    //建立一個排序條件,也就是一個NSSortDescriptor對象

    //其中第一個參數為數組中對象要按照什麼屬性來排序(比如自身、姓名,年齡等)

    //第二個參數為指定排序方式是升序還是降序

    //ascending  排序的意思,預設為YES 升序

    NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];

    NSArray *newArray = [array sortedArrayUsingDescriptors:@[des]];

    NSLog(@"%@",newArray);

 

   可以實現第一排序條件和第二排序條件

    建立一個Person類

    Person *p1 = [[Person alloc] initWithName:@"zhonger" age:@"19"];

    Person *p2 = [[Person alloc] initWithName:@"zhubada" age:@"11"];

    Person *p3 = [[Person alloc] initWithName:@"zhubada" age:@"1"];

    Person *p4 = [[Person alloc] initWithName:@"zhubada" age:@"33"];

    Person *p5 = [[Person alloc] initWithName:@"hehehe" age:@"38"];

    NSArray *person = @[p1, p2, p3, p4, p5];

    NSSortDescriptor *des1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];

    NSSortDescriptor *des2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];

    NSArray *newArray1 = [person sortedArrayUsingDescriptors:@[des1,des2]];

    NSLog(@"%@",newArray1);

    /*

     使用NSSortDesriptor進行數組排序有三步

     1.建立一個用來排序的數組

     2.建立一個排序條件,初始化中需要指定按照數組中對象的什麼屬性進行排序,升序或者降序

     3.數組根據排序條件進行排序,得到一個排序之後的數組(如果是可變數組,不會產生新數組,還是本身)

     */

    使用的sortedArrayUsingSelecor:的方法,就不需要建立NSSortDescriptor

    NSArray *strArray = @[@"zhonger", @"zhubada", @"qiuxiang", @"tangbohu", @"honghuang"];

    NSArray *nesStr = [strArray sortedArrayUsingSelector:@selector(compare:)]; //SEL  只能用@selector(方法名)給定,並且,如果數組使用這個數組進行排序,此方法必須是傳回值為NSComparisionResult

    NSLog(@"newStr is %@",nesStr);

 

    NSArray *personNewArray = [person sortedArrayUsingSelector:@selector(compareByName:)];

    NSLog(@"--%@",personNewArray);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.