首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

Objective-C 集合類完全指南:NSArray、NSSet、NSDictionary 及其可變版本實戰

     編輯:關於C

核心類別體系

不可變可變子類特性
NSArrayNSMutableArray有序、可重複、下標訪問
NSSetNSMutableSet無序、唯一、高效查找
NSDictionaryNSMutableDictionary鍵值映射、鍵唯一、Key 需遵循 NSCopying

只能存儲 Objective-C 對象,基本類型需封裝為 NSNumber、NSValue。

一、NSArray / NSMutableArray 實戰

創建

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 / NSMutableSet 實戰

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 / NSMutableDictionary 實戰

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"}];  // 完全替換

四、URL 解析實例:componentsSeparatedByString

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

五、性能特徵速查

操作NSArrayNSSetNSDictionary
按索引訪問O(1)——
按鍵/值查找O(N)O(1) 平均O(1) 平均
插入/刪除O(N) 尾部 O(1)O(1) 平均O(1) 平均
枚舉順序固定不定不定

六、最佳實踐建議

  1. 優先用字面量語法 @[]、@{},代碼更簡潔
  2. 只讀場景用不可變版本,線程安全、語義清晰
  3. 大量插入時預分配容量:[NSMutableArray arrayWithCapacity:1000]
  4. 鍵必須實現 copyWithZone: (遵循 NSCopying),通常用 NSString
  5. 跨線程傳遞集合時,考慮 copy 或加鎖

總結

Foundation 集合類是 iOS/macOS 開發基石。掌握 三大不可變類 + 三大可變子類 的創建、訪問、遍歷、增刪改查、性能特徵,並熟練使用現代字面量語法與 Block 遍歷,能顯著提升開發效率與代碼質量。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved