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

Objective-C 集合類深度解析:NSSet 與 NSMutableSet 完全指南

     編輯:關於C語言

NSSet 核心特性

  • 無序、不重複的物件集合;
  • 查找效率極高(哈希表實現),適合頻繁判斷「是否包含」;
  • 不可變,對應可變子類 NSMutableSet。

常用建構方法

// 不可變
NSSet *set1 = [NSSet set];                     // 空集合
NSSet *set2 = [NSSet setWithObject:@"abc"];    // 單元素
NSSet *set3 = [NSSet setWithObjects:obj1, obj2, @"str", nil]; // 多元素

// 可變
NSMutableSet *mset = [NSMutableSet set];
[mset addObject:obj];
[mset addObjectsFromArray:@[@"a", @"b"]];
[mset removeObject:@"a"];
[mset removeAllObjects];

核心操作

操作方法說明
元素個數count返回 NSUInteger
任意取一元素anyObject無序,僅供檢查
包含判斷containsObject: / member:返回 BOOL
轉陣列allObjects返回 NSArray(順序不定)
快速遍歷for (id obj in set)不保證順序
集合運算unionSet:, intersectSet:, isEqualToSet:, intersectsSet:並集、交集、相等、是否有交集

NSMutableSet 進階用法

NSMutableSet *setA = [NSMutableSet setWithObjects:@"a", @"b", @"c", nil];
NSMutableSet *setB = [NSMutableSet setWithObjects:@"c", @"d", @"e", nil];

[setA unionSet:setB];        // setA 變為 {a,b,c,d,e}
[setA intersectSet:setB];    // setA 變為 {c}
BOOL equal = [setA isEqualToSet:setB];
BOOL hasCommon = [setA intersectsSet:setB];

效能提示

  • 大量資料去重、成員檢查首選 NSSet(O(1) 平均查找);
  • 需保持順序或允許重複時改用 NSArray;
  • 自訂物件放入 Set 必須正確實作 isEqual: 與 hash。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved