OC之NSSet/NSMutableSet

1、集合(NSSet)與數組(NSArray)比較:算法

(1)都是存儲不一樣的對象的地址數組

(2)NSArray是有序的集合,NSSet是無序的集合。spa

(3)集合是一種哈希表,運用散列算法,查找集合中的元素比數組速度更快,可是它沒有順序。對象

2NSSet用法:索引

set集合:three

NSSet * set= [[NSSet alloc] initWithObjects:rem

@"one",@"two",@"three",@"four", nil];it

set2集合:io

NSSet * set2 = [[NSSet alloc] initWithObjects:table

@"one",@"two",@"three",@"four", nil];

1)返回集合中對象的個數

[set count];

2)判斷集合中是否擁有某個元素

判斷集合中是否擁有@」two」:

BOOL ret = [set containsObject:@"two"];

3)判斷兩個集合是否相等

BOOL ret = [set isEqualToSet:set2];

4)判斷set是不是set2的子集合

BOOL ret = [set isSubsetOfSet:set2];

5)集合也能夠用枚舉器來遍歷

NSEnumerator * enumerator = [set objectEnumerator];

NSString *str;

while(str =[enumerator nextObject])

{

……

}

6)數組轉換爲集合

NSArray * array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

 

NSSet * set= [[NSSet alloc] initWithArray:array];

7)集合轉換爲數組

NSArray * array2 = [set allObjects];

3、可變集合NSMutableSet

NSMutableSet用法:

NSMutableSet * set=[[NSMutableSet alloc] init];

1)添加元素

[setaddObject:@"one"];

[setaddObject:@"two"];

[setaddObject:@"two"];

若是添加的元素有重複,實際只保留一個刪除元素

(1)刪除元素

(a)刪除指定元素:

[set removeObject:@"two"];

(b)刪除全部元素:

[set removeAllObjects];

3)將set2中的元素添加到set

set2中的元素添加到set中來,若是有重複,只保留一個

NSSet * set2 = [[NSSet alloc] initWithObjects:@"two",@"three",@"four", nil];

[set unionSet:set2];

4)刪除set中與set2相同的元素

[set minusSet:set2];

4、指數集合(索引集合)NSIndexSet

NSIndexSet * indexSet = [[NSIndexSet alloc] initWithIndexesInRange:

NSMakeRange(1, 3)];

1)根據集合提取數組中指定位置的元素

NSArray * array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

 

NSArray * newArray = [array objectsAtIndexes:indexSet];

返回@"two",@"three",@"four"

5、可變指數集合NSMutableIndexSet

NSMutableIndexSet *indexSet =[[NSMutableIndexSet alloc] init];

[indexSet addIndex:0]

[indexSet addIndex:3];

[indexSet addIndex:5];

經過集合獲取數組中指定的元素

NSArray *array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four",@"five",@"six", nil];

 

NSArray *newArray = [array objectsAtIndexes:indexSet];

返回@"one"@"four"@"six"

相關文章
相關標籤/搜索