-集合:集合(NSSet)和數組(NSArray)有相似之處,都是存儲不同的對象的地址;不過NSArray是有序的集合,NSSet是無序的集合。
集合是一種哈希表,運用散列算法,查找集合中的元素比數組速度更快,但是它沒有順序。
NSSet*set=[[NSSet alloc]initWithObjects:@"one",@"two",@"three",@"four", nil];
[set count]; //返回集合中對象的個數
- 判斷集合中是否擁有某個元素
判斷集合中是否擁有@“two”
BOOL ret = [set containsObject:@"two"];
- 判斷兩個集合是否相等
NSSet*set2=[[NSSet alloc]initWithObjects:@"one",@"two",@"three",@"four", nil];
//判斷兩個集合是否相等
BOOL ret = [set isEqualToSet:set2];
- 判斷set是否是set2的子集合
NSSet*set2=[[NSSet alloc]initWithObjects:@"one",@"two",@"three",@"four",@"five", nil];
//判斷set是否是set2的子集合
BOOL ret = [set isSubsetOfSet:set2];
- 集合也可以用枚舉器來遍歷
//集合也可以用枚舉器來遍歷
NSEnumeratorenumerator=[set objectEnumerator];
NSStringstr;
while (str = [enumerator nextObject]) {
……
}
- 通過數組來初始化集合(數組轉換為集合)
NSArray*array=[[NSArray alloc]initWithObjects:@"one",@"two",@"three",@"four", nil];
NSSet *set=[[NSSet alloc] initWithArray:array];
- 集合轉換為數組
NSArray * array2 = [set allObjects];
可變集合NSMutableSet
//可變集合NSMutableSet
NSMutableSet * set = [[NSMutableSet alloc] init];
[set addObject:@"one"];
[set addObject:@"two"];
[set addObject:@"two"]; //如果添加的元素有重復,實際只保留一個
刪除元素
//刪除元素
[set removeObject:@"two"];
[set removeAllObjects];
- 將set2中的元素添加到set中來,如果有重復,只保留一個
//將set2中的元素添加到set中來,如果有重復,只保留一個
NSSet * set2 = [[NSSet alloc] initWithObjects:@"two",@"three",@"four", nil];
[set unionSet:set2];
- 刪除set中與set2相同的元素
[set minusSet:set2];
- 指數集合(索引集合)NSIndexSet
//指數集合(索引集合)NSIndexSet
NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 3)]; //集合中的數字是123
- 根據集合提取數組中指定位置的元素
//根據集合提取數組中指定位置的元素
NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];
NSArray * newArray = [array objectsAtIndexes:indexSet];
//返回@"two",@"three",@"four"
- 可變指數集合NSMutableIndexSet
復制代碼
NSMutableIndexSet indexSet = [[NSMutableIndexSet alloc] init];
[indexSet addIndex:0]
[indexSet addIndex:3];
[indexSet addIndex:5];
//通過集合獲取數組中指定的元素
NSArrayarray=[[NSArray alloc]initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six", nil];
NSArray *newArray = [array objectsAtIndexes:indexSet]; //返回@"one",@"four",@"six"
復制代碼