1 int main(int argc, const char * argv[]) {
2 @autoreleasepool {
3
4 //创建一个集合对象 注:如果集合中写了两次或多次同一个对象 打印只能看到一个
5 NSSet *set1 = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"three", nil];
6 //注:集合里面最外层先是大括号 然后小括号
7 //集合是无序 它是哈希散列排序 《数据结构》哈希算法
8 NSLog(@"%@",set1);
9
10 //集合中元素的个数
11 NSLog(@"集合的个数:%ld",[set1 count]);
12
13
14 //是否包含某个元素
15 BOOL contains = [set1 containsObject:@"two"];
16 NSLog(@"是否包含:%d",contains);
17
18 //两个集合是否相等
19 NSSet *set2 = [NSSet setWithObjects:@"one",@"two",@"three",@"four", nil];
20 BOOL isEqual = [set1 isEqualToSet:set2];
21
22 if (isEqual) {
23 NSLog(@"两个集合相等");
24 }else {
25 NSLog(@"两个集合不相等");
26 }
27
28
29 //判断第一个集合是否是第二个集合的子集合
30
31 BOOL isSubset = [set1 isSubsetOfSet:set2];
32 NSLog(@"是否是子集合:%d",isSubset);
33
34
35 //枚举遍历 for while do-while forin 枚举器
36 //取set2的集合枚举器 经常用枚举器遍历集合
37 NSEnumerator *enumerator = [set2 objectEnumerator];
38 NSString *str;
39 //nextObject 下一个元素
40 while (str = [enumerator nextObject]) {
41 NSLog(@"%@",str);
42 }
43
44 //通过数组的方式去创建集合 (数组转成集合)
45 NSSet *set3 = [NSSet setWithArray:@[@"one",@"five"]];
46 NSLog(@"set3:%@",set3);
47 //查看集合所有元素 返回一个数组 (集合转成数组)
48 NSArray *array1 = [set3 allObjects];
49 NSLog(@"array1:%@",array1);
50
51
52 /********可变集合*******/
53 //创建空的集合
54 NSMutableSet *mSet = [[NSMutableSet alloc] init];
55 NSLog(@"%@",mSet);
56
57 //增
58 //增加集合元素
59 [mSet addObject:@"one"];
60 [mSet addObject:@"one"];
61 [mSet addObject:@"two"];
62 [mSet addObject:@"three"];
63 NSLog(@"%@",mSet);
64
65 //删
66 //删除集合元素
67 [mSet removeObject:@"one"];
68 NSLog(@"%@",mSet);
69
70
71 //集合中添加集合
72 [mSet unionSet:set2];
73 NSLog(@"------%@",mSet);
74
75 //集合中删除集合 删除的时候 如果要删除集合里面有多的集合元素,mSet没有此集合元素 删除的时候不会崩溃
76 // NSSet *_set = [NSSet setWithObjects:@"one",@"two",@"three",@"four",@"1", nil];
77
78 // [mSet minusSet:_set];
79 // NSLog(@"======%@",mSet);
80
81 /********指数集合或索引集合**********/
82 //继承NSObject
83 //创建一个索引集合 通过在指定范围创建索引集合 注:range千万别超范围会崩溃
84 // NSIndexSet *set4 = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(2, 4)];
85
86 //创建一个空的可变的索引集合
87 NSMutableIndexSet *set5 = [[NSMutableIndexSet alloc] init];
88 //给可变索引集合添加下标
89 [set5 addIndex:0];
90 [set5 addIndex:2];
91 [set5 addIndex:3];
92 [set5 addIndex:6];
93
94
95 NSArray *allArray = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six",@"seven", nil];
96 //通过索引集合得到数组(索引range范围内的数组元素)
97 NSArray *subArray = [allArray objectsAtIndexes:set5];
98 NSLog(@"++++++++%@",subArray);
99
100
101 }
102 return 0;
103 }