您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C 中 NSArray 的排序與遍歷用法示例

編輯:iOS 開發綜合

NSArray 是 Objective-C 中最基礎的有序集合,掌握它的排序與遍歷是每個 iOS 開發者的必修課。本文從多種排序策略一路談到四種遍歷方式,並附上可直接套用的範例。

一、NSArray 的四種排序方式

1. 使用系統內建的 compare: 方法

當元素本身(例如 NSString)已實現 compare: 時,可直接透過 sortedArrayUsingSelector: 排序:

void arraySort1() {
    NSArray *array = [NSArray arrayWithObjects:@"2", @"3", @"1", @"4", nil];
    // 指定系統自帶的比較方法 compare:
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"%@", array2);
}

2. 自定義比較方法

類似 Java 中的 compareTo,我們可以在自定義類裡實作比較邏輯(此方法名為 compareStudent:),再交給排序方法調用:

void arraySort2() {
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao"];
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng"];
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong"];
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng"];

    NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, stu4, nil];
    // 使用自定義的比較方法,前提是類中已實現該方法
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];
    NSLog(@"%@", array2);
}

對應 Student 類中的比較實作如下:

- (NSComparisonResult)compareStudent:(Student *)stu {
    NSComparisonResult result = [self.firstName compare:stu.firstName];
    if (result == NSOrderedSame) {
        // 名字相同時再比較姓氏
        result = [self.lastName compare:stu.lastName];
    }
    return result;
}

3. 使用 Block 排序

Block 讓比較邏輯直接寫在排序調用處,不必另外定義方法,更加直觀:

void arraySort3() {
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao"];
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng"];
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong"];
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng"];

    NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, stu4, nil];
    NSArray *array2 = [array sortedArrayUsingComparator:^NSComparisonResult(Student *obj1, Student *obj2) {
        NSComparisonResult result = [obj1.firstName compare:obj2.firstName];
        if (result == NSOrderedSame) {
            result = [obj1.lastName compare:obj2.lastName];
        }
        return result;
    }];
    NSLog(@"%@", array2);
}

4. 使用 NSSortDescriptor 進行高級排序

NSSortDescriptor 支援多條件、多層級排序,甚至能透過 keyPath 存取關聯對象的屬性,是處理複雜排序時最靈活的選擇:

void arraySort4() {
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao" bookName:@"lianai"];
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng" bookName:@"tianshi"];
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong" bookName:@"love"];
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng" bookName:@"qingren"];

    NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, stu4, nil];

    // 建立多個排序描述子,keyPath 可跨對象存取(如 book.name)
    NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES];
    NSSortDescriptor *firstNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
    NSSortDescriptor *lastNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];

    NSArray *array2 = [array sortedArrayUsingDescriptors:
                       [NSArray arrayWithObjects:bookNameDesc, firstNameDesc, lastNameDesc, nil]];
    NSLog(@"%@", array2);
}

二、NSArray 的基本與高級 API

需要先牢記一個前提:NSArray 只能存放 OC 對象,且不能裝入空值(nil),因為 nil 在初始化列表中代表「元素結束」的標記。

// 基本用法
NSArray *array = [NSArray array];                          // 空數組
array = [NSArray arrayWithObject:@"123"];                  // 單元素
array = [NSArray arrayWithObjects:@"a", @"b", nil];        // 多元素,結尾必須是 nil
array = [NSArray arrayWithArray:array];                    // 用另一個數組初始化

int count = [array count];                                 // 元素個數,等同 array.count
[array containsObject:@"a"];                               // 是否包含某元素
[array lastObject];                                        // 最後一個元素
[array objectAtIndex:0];                                   // 指定下標的元素
[array indexOfObject:@"a"];                                // 元素所在位置
[array isEqualToArray:otherArray];                         // 比較兩個集合內容是否相同
[array firstObjectCommonWithArray:otherArray];             // 兩個集合中第一個相同的元素
// 高級用法
[array makeObjectsPerformSelector:@selector(someMethod)];          // 讓所有元素執行某方法
[array makeObjectsPerformSelector:@selector(someMethod) withObject:arg]; // 帶一個參數
[array arrayByAddingObject:anObject];                             // 返回追加元素後的新數組
[array arrayByAddingObjectsFromArray:otherArray];                 // 返回合併後的新數組
[array subarrayWithRange:range];                                  // 截取指定範圍
[array componentsJoinedByString:@","];                            // 拼接成字符串
[array writeToFile:path atomically:YES];                          // 持久化到文件

要留意 arrayByAdding... 這類方法不會改變原數組,而是返回一個全新的 NSArray。

三、NSArray 的四種遍歷方式

方式一:傳統 for 循環

void arrayFor1() {
    NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
    int count = array.count;
    for (int i = 0; i < count; i++) {
        id obj = [array objectAtIndex:i];
        NSLog(@"%i-%@", i, obj);
    }
}

方式二:快速遍歷(fast enumeration)

void arrayFor2() {
    NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
    int i = 0;
    for (id obj in array) {
        NSLog(@"%i-%@", i, obj);
        i++;
    }
}

方式三:使用 Block 遍歷

Block 回調提供三個參數:obj 為當前元素、idx 為下標、stop 為一個可提前終止遍歷的布爾輸出參數(將其設為 YES 即可跳出循環):

void arrayFor3() {
    NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"%zi->%@", idx, obj);
        // *stop = YES; // 取消註解即可提前終止遍歷
    }];
}

若需要控制遍歷方向,可改用帶 options 的版本,例如傳入 NSEnumerationReverse 即可從尾向頭遍歷:

[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id str, NSUInteger index, BOOL *te) {
    NSLog(@"%@,%d", str, index);
}];

方式四:使用 NSEnumerator 迭代器

迭代器可用於遍歷集合,NSArray 提供了正序與反序兩種迭代器:objectEnumerator(正序)與 reverseObjectEnumerator(反序)。常用方法有 nextObject(取下一個元素)與 allObjects(取回全部元素)。

void arrayFor4() {
    NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
    NSEnumerator *enumerator = [array objectEnumerator];

    // 注意:若在遍歷之後才調用 allObjects,會取到空,因為迭代器已耗盡
    NSArray *array2 = [enumerator allObjects];
    NSLog(@"array2=%@", array2);

    id obj = nil;
    while (obj = [enumerator nextObject]) {
        NSLog(@"obj=%@", obj);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved