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

Objective-C NSSet/NSMutableSet 完全指南:集合創建、查詢、集合運算、可變修改

     編輯:關於C語言

核心特性

  • 無序:元素無固定順序
  • 唯一:同一對象(isEqual: 判定)僅保存一份
  • NSSet 不可變;NSMutableSet 可變
  • 只存對象,基本類型需包裝

NSSet 不可變集合

創建


// 直接創建
NSSet *set1 = [NSSet setWithObjects:@"one", @"two", nil];

// 從數組
NSArray *arr = @[@"a", @"b", @"a"]; // 重複元素
NSSet *set2 = [NSSet setWithArray:arr]; // 自動去重 → {a, b}

// 從集合
NSSet *set3 = [NSSet setWithSet:set2];

查詢操作


NSUInteger count = [set3 count];           // 元素個數
NSArray *all = [set3 allObjects];          // 所有元素轉數組 (順序不定)
id any = [set3 anyObject];                 // 任意一個元素
BOOL has = [set3 containsObject:@"two"];   // 是否包含
BOOL equal = [set1 isEqualToSet:set2];     // 集合相等 (同元素)
BOOL subset = [set1 isSubsetOfSet:set2];   // 是否子集
BOOL intersect = [set1 intersectsSet:set2]; // 是否有交集

派生新集合


// 添加元素返回新集合
NSSet *set4 = [set1 setByAddingObject:@"three"];

// 添加集合返回新集合
NSSet *set5 = [set1 setByAddingObjectsFromSet:set2];

// 添加數組返回新集合
NSSet *set6 = [set1 setByAddingObjectsFromArray:@[@"x", @"y"]];

NSMutableSet 可變集合

創建


NSMutableSet *mset1 = [NSMutableSet set];                    // 空
NSMutableSet *mset2 = [NSMutableSet setWithObjects:@"1", @"2", nil];
NSMutableSet *mset3 = [NSMutableSet setWithObjects:@"a", @"2", nil];

集合運算(原地修改)


// 差集:移除 mset3 中也存在的元素
[mset2 minusSet:mset3]; // mset2 = mset2 - mset3

// 交集:保留雙方都有的元素
[mset2 intersectSet:mset3]; // mset2 = mset2 ∩ mset3

// 並集:合併元素
[mset2 unionSet:mset3]; // mset2 = mset2 ∪ mset3

元素增刪


[mset2 addObject:@"new"];           // 添加
[mset2 removeObject:@"old"];        // 刪除指定
[mset2 removeAllObjects];           // 清空

NSSet vs NSArray 選擇指南

性能與實現細節

  • 底層:哈希表,hash + isEqual: 確定唯一性
  • 自定義對象作元素:必須同時實現 isEqual: 和 hash,且相等對象哈希值必相等
  • NSSet 不可變 → 線程安全;NSMutableSet 非線程安全
  • 大量元素預知規模:[NSMutableSet setWithCapacity:1000]

枚舉遍歷


// 快速枚舉
for (id obj in set) { ... }

// Block 枚舉
[set enumerateObjectsUsingBlock:^(id obj, BOOL *stop) { ... }];

// 迭代器
NSEnumerator *en = [set objectEnumerator];
while (id obj = [en nextObject]) { ... }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
需求推薦理由
頻繁查找是否包含NSSetO(1) 哈希查找 vs O(n) 線性掃描
需要保持插入順序NSArray有序 vs 無序
自動去重NSSet集合語義天然去重
需要下標訪問NSArray支持 objectAtIndex: vs 不支持
集合運算 (交/並/差)NSSet內置高效實現