集合(NSSet)是一组单值对象的组合,集合对象的操作包括:搜索,添加,删除集合中的成员(可变集合的功能),比较两个集合,计算两个集合的交集,并集等。
下面来看下(NSSet)的方法:
1)集合的构建
1 // 构建集合的三种方法
2
3 #import <Foundation/Foundation.h>
4
5 int main(int argc , const char *argv[]){
6 @autoreleasepool {
7 NSSet *set1 = [NSSet setWithObjects:@"zhangsan",@"lisi",@"wangwu",nil];
8 for(NSString *temp1 in set1){
9 NSLog(@"temp1 = %@",temp1);
10 }
11
12 NSArray *array = @[@"aa",@"bb",@"cc"];
13 NSSet *set2 = [NSSet setWithArray:array];
14 for(NSString *temp2 in set2)
15 NSLog(@"temp2 = %@",temp2);
16
17 NSSet *set3 = [[NSSet alloc] initWithObjects:@"aa",@"bb"@"cc",nil];
18 for(NSString *temp3 in set3)
19 NSLog(@"temp3 = %@",temp3);
20 }
21 }
2)集合的遍历
1 #import <Foundation/Foundation.h>
2
3 @interface NSString (print)
4
5 - (void)print;
6 - (void)show:(NSString *)str;
7
8 @end
9
10 @implementation NSString (print)
11
12 - (void)print{
13 NSLog(@"%@",self);
14 }
15 - (void)show:(NSString *)str{
16 NSLog(@"%@ : %@",str,self);
17 }
18
19 @end
20 int main(int argc , const char *argv[]){
21 @autoreleasepool {
22 NSSet *set = [NSSet setWithObjects:@"zhangsan",@"lisi",@"wangwu",nil];
23 for(NSString *temp in set)
24 NSLog(@"temp = %@",temp);
25
26 NSLog(@"--------------------------");
27 [set enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
28 NSLog(@"obj = %@",obj);
29 }];
30
31 NSLog(@"---------------------------");
32 [set makeObjectsPerformSelector:@selector(print)];
33
34 NSLog(@"----------------------------");
35 [set makeObjectsPerformSelector:@selector(show:) withObject:@"this is "];
36
37 NSLog(@"-----------------------------");
38 NSEnumerator *emr = [set objectEnumerator];
39 NSString *temp = nil;
40 while(temp = [emr nextObject])
41 NSLog(@"temp = %@",temp);
42 }
43 return 0;
44 }
3) 集合的比较
1 #import <Foundation/Foundation.h>
2
3 int main(int argc , const char *argv[]){
4 @autoreleasepool {
5 NSSet *set = [NSSet setWithObjects:@"zhangsan",@"lisi",@"wangwu",nil];
6 for(NSString *temp in set)
7 NSLog(@"temp = %@",temp);
8
9 BOOL ishas = [set containsObject:@"lisi"];
10 if(ishas)
11 NSLog(@"has lisi");
12 else
13 NSLog(@"no lisi");
14
15 NSString *str = [set member:@"aaaa"];
16 NSLog(@"str = %@",str);
17
18 NSSet *set2 = [set setByAddingObject:@"xiaoliu"];
19 NSLog(@"set2 = %@",set2);
20
21 NSSet *set3 = [set setByAddingObjectsFromArray:@[@"aa",@"bb",@"cc"]];
22 NSLog(@"set3 = %@",set3);
23
24 NSSet *set4 = [NSSet setWithObjects:@"zhangsan",@"lisi",nil];
25 BOOL issub = [set4 isSubsetOfSet:set];
26 if(issub)
27 NSLog(@"set4 is set sub class");
28 else
29 NSLog(@"set4 no set sub class");
30
31 BOOL isinterset = [set intersectsSet:set4];
32 if(isinterset)
33 NSLog(@"set and set4 has in