码迷,mamicode.com
首页 > 其他好文 > 详细

OC中的集合NSSet

时间:2015-06-08 23:10:14      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

 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

 

OC中的集合NSSet

标签:

原文地址:http://www.cnblogs.com/sdutmyj/p/4562122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!