NSHashTable
類似于集合的集合袄膏,但具有更廣泛的可用內(nèi)存語義。繼承自NSObject掺冠;NSHashTable具有以下特點(diǎn):
- 它是內(nèi)容可變的沉馆;
- 可以容納對(duì)其成員的弱引用;
- 成員可以在輸入上復(fù)制,也可以使用指針標(biāo)識(shí)進(jìn)行相等和散列斥黑;
- 可以包含任意指針(其成員不限于作為對(duì)象)揖盘;
創(chuàng)建
// 根據(jù)選項(xiàng)創(chuàng)建哈希表
NSHashTable *hashTable = [[NSHashTable alloc]initWithOptions:NSPointerFunctionsStrongMemory capacity:5];
NSPointerFunctions *functions = [[NSPointerFunctions alloc]initWithOptions:NSPointerFunctionsStrongMemory];
// 根據(jù)方法創(chuàng)建哈希表
NSHashTable *hashTable1 = [[NSHashTable alloc]initWithPointerFunctions:functions capacity:5];
// 創(chuàng)建存儲(chǔ)弱引用內(nèi)容的哈希表
NSHashTable *hashTable2 = [NSHashTable weakObjectsHashTable];
// 創(chuàng)建指定指針函數(shù)選項(xiàng)的哈希表
NSHashTable *hashTable3 = [NSHashTable hashTableWithOptions:NSPointerFunctionsStrongMemory];
訪問內(nèi)容
NSHashTable *hashTable = [[NSHashTable alloc]initWithOptions:NSPointerFunctionsStrongMemory capacity:5];
[hashTable addObject:@"1"];
[hashTable addObject:@"2"];
[hashTable addObject:@"3"];
// 獲取哈希表中的一個(gè)對(duì)象
NSString *anyObj = [hashTable anyObject];//1
// 獲取哈希表中全部對(duì)象
NSArray *objArr = [hashTable allObjects];//(1,2,3)
// 包含哈希表元素的集合
NSSet *set = [hashTable setRepresentation];//{(1,3,2)}
// 獲取哈希表中的元素?cái)?shù)量
NSUInteger count = [hashTable count];//3
// 判斷哈希表中是否包含指定元素
BOOL isCon = [hashTable containsObject:@"1"];//YES
// 確定哈希表是否包含給定對(duì)象,并返回該對(duì)象(如果存在)
NSString *obj = [hashTable member:@"1"];//1
// 根據(jù)枚舉器遍歷哈希表元素
NSEnumerator *enumerator = [hashTable objectEnumerator];
id object;
while (object = [enumerator nextObject]) {
NSLog(@"開始打有颗:%@\n",object);
/*
開始打邮尴痢:1
開始打印:3
開始打勇故瘛:2
*/
}
訪問內(nèi)容
NSHashTable *hashTable = [[NSHashTable alloc]initWithOptions:NSPointerFunctionsStrongMemory capacity:5];
// 將指定對(duì)象添加到哈希表
[hashTable addObject:@"1"];
// 從哈希表中移除指定元素
[hashTable removeObject:@"1"];
// 從哈希表中刪除所有元素
[hashTable removeAllObjects];
比較哈希表
NSHashTable *hashTable = [[NSHashTable alloc]initWithOptions:NSPointerFunctionsStrongMemory capacity:5];
[hashTable addObject:@"1"];
[hashTable addObject:@"2"];
[hashTable addObject:@"3"];
[hashTable addObject:@"4"];
[hashTable addObject:@"5"];
NSHashTable *hashTable1 = [[NSHashTable alloc]initWithOptions:NSPointerFunctionsStrongMemory capacity:5];
[hashTable1 addObject:@"3"];
[hashTable1 addObject:@"4"];
[hashTable1 addObject:@"5"];
[hashTable1 addObject:@"6"];
[hashTable1 addObject:@"7"];
// 給定的哈希表是否與接收哈希表相交
BOOL isIn = [hashTable intersectsHashTable:hashTable1];//YES
// 接收哈希表中的每個(gè)元素是否也存在于另一個(gè)給定哈希表中椭符。
BOOL isSub = [hashTable isSubsetOfHashTable:hashTable1];//NO
// 指示給定的哈希表是否等于接收哈希表。
BOOL isEq = [hashTable isEqualToHashTable:hashTable1];//NO
// 從接收哈希表中刪除另一個(gè)給定哈希表中的每個(gè)元素(如果存在)
[hashTable minusHashTable:hashTable1];//(1,2)
// 將另一個(gè)給定哈希表中的每個(gè)元素添加到接收哈希表(如果不存在)耻姥。
[hashTable unionHashTable:hashTable1];//(1,6,2,5,7,3,4)
// 從接收哈希表中刪除不是另一個(gè)給定哈希表的成員的每個(gè)元素销钝。
[hashTable intersectHashTable:hashTable1];//(6,5,7,3,4)