Objective-C之foundation中四種數組NSArray的排序方法

來源:互聯網
上載者:User

demo代碼如下:
數組排序有四種方法:
1、基本排序方式:
利用NSString中提供的compare方法進行排序,見demo的arraySort1
2、自訂compare
在實體類中自訂compareStudent方法,實現排序邏輯
3、利用block進行排序:
sortedArrayUsingComparator
4、進階排序方法
利用排序描述器,自訂排序優先順序

Book.h檔案:
#import <Foundation/Foundation.h>
@interface Book : NSObject

@property (nonatomic, retain) NSString * name;
+ (id) bookWithName:(NSString *) name;
@end

Book.m檔案:
#import "Book.h"
#import "Book.h"

@implementation Book
+(id) bookWithName:(NSString *)name{
    Book *book = [[[Book alloc] init] autorelease];
    book.name = name;
    return book;
}

- (void)dealloc{
    [_name release];
    [super dealloc];
}
@end

Student.h檔案:
#import <Foundation/Foundation.h>

@class Book;
@interface Student : NSObject

@property (nonatomic, retain) NSString *firstname;
@property (nonatomic, retain) NSString *lastname;
@property (nonatomic, retain) Book *book;

+ (id) studentWithFirstname:(NSString *)firstname  lastname:(NSString *) lastname;
+ (id) studentWithFirstname:(NSString *)firstname  lastname:(NSString *) lastname bookName:(NSString *) bookName;

- (NSComparisonResult)compareStudent:(Student *)stu;
@end

Student.m檔案:

#import "Student.h"
#import "Book.h"
@implementation Student

+ (id)studentWithFirstname:(NSString *)firstname lastname:(NSString *)lastname{
    Student *stu = [[[Student alloc] init] autorelease];
    stu.firstname = firstname;
    stu.lastname = lastname;
    return stu;
}

+ (id)studentWithFirstname:(NSString *)firstname lastname:(NSString *)lastname bookName:(NSString *)bookName{
    Student *stu = [Student studentWithFirstname:firstname lastname:lastname];
    stu.book = [Book bookWithName:bookName];
     
    return stu;
}

//傳回值類型必須是NSComparisonResult
- (NSComparisonResult) compareStudent:(Student *)stu{
   //姓進行排序
    NSComparisonResult result = [self.lastname compare: stu.lastname];
    //如果姓相同,則根據名排序
    if(result == NSOrderedSame){
        result = [self.firstname compare:stu.firstname];
    }
    return result;
}
//重寫description方法
- (NSString *) description{
  return   [NSString stringWithFormat:@"%@
%@-%@",self.lastname, self.firstname,self.book.name];
}

- (void) dealloc{
    [_firstname release];
    [_lastname release];
    [_book release];
    [super dealloc];
}

@end

main測試檔案:

#import <Foundation/Foundation.h>
#import "Student.h"

#pragma mark sort1
void arraySort1(){
    NSArray *array = [NSArray arrayWithObjects:@"1",@"5",@"2",@"8",@"3", nil];
    //指定元素的比較方法compare
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"array2:%@", array2);
}

void arraySort2(){

    Student *stu1=[Student studentWithFirstname:@"1" lastname:@"wang"];
    Student *stu2=[Student studentWithFirstname:@"1" lastname:@"li"];
    Student *stu3=[Student studentWithFirstname:@"2" lastname:@"wang"];
    Student *stu4=[Student studentWithFirstname:@"3" lastname:@"zhang"];

    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil];
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];
    NSLog(@"%@", array2);
}

void arraySort3(){
    Student *stu1=[Student studentWithFirstname:@"1" lastname:@"wang"];
    Student *stu2=[Student studentWithFirstname:@"1" lastname:@"li"];
    Student *stu3=[Student studentWithFirstname:@"2" lastname:@"wang"];
    Student *stu4=[Student studentWithFirstname:@"3" lastname:@"zhang"];
   
    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil];

    NSArray *array2 = [array sortedArrayUsingComparator:^NSComparisonResult(Student *obj1, Student *obj2) {
        //姓進行排序
        NSComparisonResult result = [obj1.lastname compare: obj2.lastname];
        //如果姓相同,則根據名排序
        if(result == NSOrderedSame){
            result = [obj1.firstname compare:obj2.firstname];
        }
        return result;
    }];

    NSLog(@"array2:%@",array2);
}
#pragma mark 自訂優先順序排序
void arraySort4(){
    Student *stu1=[Student studentWithFirstname:@"1" lastname:@"wang" bookName:@"book1"];
    Student *stu2=[Student studentWithFirstname:@"1" lastname:@"li" bookName:@"book3"];
    Student *stu3=[Student studentWithFirstname:@"2" lastname:@"wang" bookName:@"book1"];
    Student *stu4=[Student studentWithFirstname:@"3" lastname:@"zhang" bookName:@"book2"];
   
    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil];
    //建立排序描述器 @"lastname" @property後面的名字一致
    NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES];
    NSSortDescriptor *lastnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastname" ascending:YES];
    NSSortDescriptor *firstnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstname" ascending:YES];
    //按照需求要求的排序優先順序排序
    NSArray *desc = [NSArray arrayWithObjects:bookNameDesc,lastnameDesc,firstnameDesc, nil];
    NSArray *array2 = [array sortedArrayUsingDescriptors:desc];
   
    NSLog(@"array2:%@",array2);
}

int main(int argc, const char * argv[])
{

    @autoreleasepool {
       
        arraySort1();
        NSLog(@"------arraySort2------");
        arraySort2();
        NSLog(@"------arraySort3-------");
        arraySort3();
        NSLog(@"------arraySort4-------");
        arraySort4();
    }
    return 0;
}

執行列印結果:
2013-07-28 02:27:44.449 NSArray排序[3531:303] array2:(
    1,
    2,
    3,
    5,
    8
)
2013-07-28 02:27:44.473 NSArray排序[3531:303] ------arraySort2------
2013-07-28 02:27:44.475 NSArray排序[3531:303] (
    "li 1-(null)",
    "wang 1-(null)",
    "wang 2-(null)",
    "zhang 3-(null)"
)
2013-07-28 02:27:44.476 NSArray排序[3531:303] ------arraySort3-------
2013-07-28 02:27:44.478 NSArray排序[3531:303] array2:(
    "li 1-(null)",
    "wang 1-(null)",
    "wang 2-(null)",
    "zhang 3-(null)"
)
2013-07-28 02:27:44.478 NSArray排序[3531:303] ------arraySort4-------
2013-07-28 02:27:44.479 NSArray排序[3531:303] array2:(
    "wang 1-book1",
    "wang 2-book1",
    "zhang 3-book2",
    "li 1-book3"
)

聯繫我們

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