1 集合NSSet(無序) 2 本質上是哈希表,採用散列算法來查找 3 每一個元素只有一次,元素是無序的 4 5 建立 每一個元素能夠是任意的對象 6 NSSet *set=[[NSSet alloc] initWithObjects:@"one",@"two", 7 @"three",@"four",nil]; 8 NSSet *set2=[[NSSet alloc] initWithObjects:@"one",@"two", 9 @"three",@"four",@"five",nil]; 10 打印 11 NSLog(@"%@",set);結果one three four two可見是無序的 12 得到集合中的元素的個數 13 NSLog(@"%@lu",[set count]); 14 判斷集合中是否擁有某個元素 15 BOOL ret=[set containsObject:@"two"]; 16 17 判斷兩個集合是否相等 18 BOOL ret=[set isEqualToSet:set2]; 19 判斷第一個集合是不是第二個集合的子集合 20 BOOL ret=[set isSubsetOfSet:set2]; 21 22 也能夠經過枚舉器法遍歷 23 NSEnumerator *enumrator=[set objectEnumrator]; 24 枚舉器能夠遍歷數組、字典、和集合; 25 NSString *str; 26 27 while(str=[enumrator nextObject]){ 28 NSLog(@"%@",str); 29 } 30 31 集合還能夠利用從數組中提取元素來建立 32 NSArray *array=[[NSArray alloc] initWithObjects:@"one",@"two",nil]; 33 NSSet *set=[[NSSet alloc] initWithObjects:array]; 34 集合也能夠把本身的元素取出來生成數組對象 35 NSArray *array2=[set allObjects]; 36 NSLog(@"%@",array2); 37 38 [array release]; 39 [set release]; 40 41 42 NSMutableSet *set=[NSMutableSet alloc] init]; 43 動態添加,若是添加的有重複,只保留一個 44 [set addObject:@"one"]; 45 [set addObject:@"two"]; 46 [set addObject:@"one"]; 47 48 刪除 49 [set removeObject:@"two"]; 50 51 添加集合 52 NSSet *set2=[[NSSet alloc] initWithObjects:@"five",@"four",nil]; 53 [set unionSet:set2];set2中的內容所有添加到set中,重複的只保留一個 54 55 [set minusSet:set2];將set2中的內容刪除 56 57 NSIndexSet指數集合(索引集合) 58 裝的都是數字 59 NSIndexSet *indexSet=[NSIndexSet alloc] initWithIndexesInRange: 60 NSMakeRange(2,3)];從2開始3個數字,因此集合中數字是2,3,4 61 62 提取數組中的元素 63 NSArray *array=[[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six",nil]; 64 NSArray *newArray=[array objectsAtIndexes:indexSet]; 65 NSLog(@"%@",newArray);結果是 three,four,five 66 67 68 NSMutableIndexSet *indexSet=[[NSMutableIndexSet alloc]init]; 69 [indexSet addIndex:0]; 70 [indexSet addIndex:3]; 71 [indexSet addIndex:5]; 72 NSArray *array=[[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six",nil]; 73 NSArray *newArray=[array objectsAtIndexes:indexSet]; 74 NSLog(@"%@",newArray);結果是 one,four,six