一.簡介
NSSet 集合和數(shù)組(NSArray)相似,都是存儲不同對象的地址;
不過 NSArray 是有序的集合,而 NSSet 是無序的集合;
其中,集合是一種哈希表,運用散列算法查找集合中的元素;
效率相對比起數(shù)組速率更快,但它沒有順序.
NSSet *set = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];
[set count];//返回集合中對象的個數(shù)
NSMutableSet *mSet = [NSMutableSet setWithCapacity:0];
注:若在設(shè)置時放入兩個相同的元素,系統(tǒng)會自動刪掉一個元素.
二.常用方法
1.判斷集合中是否擁有某個元素 Element
//判斷集合中是否擁有@“two”
BOOL ret = [setcontainsObject:@"two"];
2.判斷兩個集合是否相等
NSSet * set2 = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];//判斷兩個集合是否相等BOOL ret = [setisEqualToSet:set2];
3.判斷 set 是否是 set2 的子集
NSSet * set2 = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five", nil];//判斷set是否是set2的子集合BOOL ret = [setisSubsetOfSet:set2];
4.集合也可以用枚舉器來遍歷
//集合也可以用枚舉器來遍歷NSEnumerator * enumerator = [setobjectEnumerator];NSString *str;while(str =[enumerator nextObject]) {……}
5.通過數(shù)組來初始化集合(數(shù)組轉(zhuǎn)為集合)
NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];NSSet *set= [[NSSet alloc] initWithArray:array];
6.集合轉(zhuǎn)換為數(shù)組
NSArray * array2 = [setallObjects];
7.可變集合 NSMutableSet
//可變集合NSMutableSetNSMutableSet *set=[[NSMutableSet alloc] init];[setaddObject:@"one"];[setaddObject:@"two"];[setaddObject:@"two"];//如果添加的元素有重復(fù),實際只保留一個
8.刪除元素
//刪除元素[setremoveObject:@"two"];[setremoveAllObjects];
9.將 set2 中的元素添加到 set 中來,若重復(fù)則保留一個
//將set2中的元素添加到set中來,如果有重復(fù),只保留一個NSSet * set2 = [[NSSet alloc] initWithObjects:@"two",@"three",@"four", nil];[setunionSet:set2];
10.刪除 set 中與 set2 相同的元素
[setminusSet:set2];
11.指數(shù)集合(索引集合)NSIndexSet
//指數(shù)集合(索引集合)NSIndexSetNSIndexSet * indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1,3)];//集合中的數(shù)字是123
12.根據(jù)集合提取數(shù)組中指定位置的元素
//根據(jù)集合提取數(shù)組中指定位置的元素NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];NSArray * newArray = [array objectsAtIndexes:indexSet];//返回@"two",@"three",@"four"
13.可變指數(shù)集合 NSMutableIndexSet
NSMutableIndexSet *indexSet =[[NSMutableIndexSet alloc] init];[indexSet addIndex:0][indexSet addIndex:3];[indexSet addIndex:5];//通過集合獲取數(shù)組中指定的元素NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six", nil];NSArray *newArray = [array objectsAtIndexes:indexSet];//返回@"one",@"four",@"six"