| 不可變 | 可變子類 | 特性 |
|---|---|---|
| NSArray | NSMutableArray | 有序、可重複、下標訪問 |
| NSSet | NSMutableSet | 無序、唯一、高效查找 |
| NSDictionary | NSMutableDictionary | 鍵值映射、鍵唯一、Key 需遵循 NSCopying |
只能存儲 Objective-C 對象,基本類型需封裝為 NSNumber、NSValue。
NSArray *arr1 = @[]; // 空數組 NSArray *arr2 = @[@"a", @"b", @"c"]; // 字面量語法 NSArray *arr3 = [NSArray arrayWithObjects:@"x", @"y", nil]; // 傳統語法
// 下標訪問
NSString *first = arr2[0];
NSString *first2 = [arr2 objectAtIndex:0];
// 1. 傳統 for
for (NSUInteger i = 0; i < arr2.count; i++) {
NSLog(@"%@", arr2[i]);
}
// 2. 快速枚舉 (推薦)
for (id obj in arr2) {
NSLog(@"%@", obj);
}
// 3. Block 遍歷 (可獲取索引、可中途停止)
[arr2 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (idx > 2) *stop = YES;
NSLog(@"%lu: %@", idx, obj);
}];
NSMutableArray *mar = [NSMutableArray array]; [mar addObject:@"a"]; [mar addObjectsFromArray:@[@"b", @"c"]]; [mar insertObject:@"first" atIndex:0]; [mar removeObjectAtIndex:1]; [mar removeObject:@"b"]; // 刪除所有匹配 [mar removeObjectsInRange:NSMakeRange(0, 1)]; [mar replaceObjectAtIndex:0 withObject:@"new"]; [mar exchangeObjectAtIndex:0 withObjectAtIndex:1];
NSSet *set = [NSSet setWithObjects:@"a", @"b", @"c", nil]; BOOL has = [set containsObject:@"b"]; // O(1) 平均 NSMutableSet *mset = [NSMutableSet set]; [mset addObject:@"x"]; [mset unionSet:[NSSet setWithObject:@"y"]]; [mset minusSet:[NSSet setWithObject:@"x"]]; [mset intersectSet:otherSet];
NSDictionary *dict = @{@"name": @"Alice", @"age": @25};
NSString *name = dict[@"name"]; // 現代語法
NSString *name2 = [dict objectForKey:@"name"];
NSMutableDictionary *md = [NSMutableDictionary dictionary];
[md setObject:@"Bob" forKey:@"name"];
[md removeObjectForKey:@"age"];
[md setDictionary:@{@"city": @"NYC"}]; // 完全替換
NSString *url = @"https://www.example.com:8080/path"; NSArray *parts1 = [url componentsSeparatedByString:@"//"]; // [http:, www.example.com:8080/path] NSArray *parts2 = [parts1[1] componentsSeparatedByString:@":"]; // [www.example.com, 8080/path] NSArray *parts3 = [[parts1 lastObject] componentsSeparatedByString:@":"]; // 同上 NSLog(@"Host: %@", parts2[0]); // www.example.com
| 操作 | NSArray | NSSet | NSDictionary |
|---|---|---|---|
| 按索引訪問 | O(1) | — | — |
| 按鍵/值查找 | O(N) | O(1) 平均 | O(1) 平均 |
| 插入/刪除 | O(N) 尾部 O(1) | O(1) 平均 | O(1) 平均 |
| 枚舉順序 | 固定 | 不定 | 不定 |
@[]、@{},代碼更簡潔[NSMutableArray arrayWithCapacity:1000]copyWithZone: (遵循 NSCopying),通常用 NSStringcopy 或加鎖Foundation 集合類是 iOS/macOS 開發基石。掌握 三大不可變類 + 三大可變子類 的創建、訪問、遍歷、增刪改查、性能特徵,並熟練使用現代字面量語法與 Block 遍歷,能顯著提升開發效率與代碼質量。