NSSet

1.NSSet是Hash表使用散列算法而生成,如果集合中又两个相同的元素,那么只生成后面的那一个

2.声明一个NSSet

NSSet *set = [[[NSSet alloc] initWithObjects:@"one",@"two",@"three", nil] autorelease];
NSSet *set1 = [[[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"five", nil] autorelease];
NSLog(@"%@",set);

    2.1.获得集合中的元素个数

NSLog(@"集合中的元素个数是:%lu",[set count]);

    2.2.查询集合中的是否包含这个元素

BOOL ret = [set containsObject:@"one"];
NSLog(@"集合中包含 one 元素吗?:%@",ret==1?@"是":@"否");
BOOL ret1 = [set containsObject:@"five"];
NSLog(@"集合中包含 five 元素吗?:%@",ret1==1?@"是":@"否");

 2.3.、判断第一个集合是否是第二个集合的子集合

BOOL judge1 = [set isSubsetOfSet:set1];
NSLog(@"第一个集合是第二个集合的子集合吗?:%@",judge1==1?@"是":@"否");

   2.4.集合的遍历

NSEnumerator * enumerator = [set1 objectEnumerator];
NSString * mystr;
while(mystr = [enumerator nextObject]){
     NSLog(@"集合中的元素是:%@",mystr);
}

   2.5.通过数组来创建一个集合

NSArray * array = [[[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil] autorelease];
NSSet * arraySet = [[NSSet alloc] initWithArray:array];
NSLog(@"通过数组的元素生成的集合:%@",arraySet);

 2.6.将集合生成数组

NSArray * setArray = [arraySet allObjects];
NSLog(@"将集合生成的数组是:%@",setArray);

3.可变几何(NSMutableSet)

   3.1.NSMutableSetNSSet的子类,除了有NSSet的方法之外,还有增删改元素的方法

   3.2.如果添加的元素有重复,实际上只是保留一个元素

 NSMutableSet * mutableSet = [[[NSMutableSet alloc] init] autorelease];
[mutableSet addObject:@"hahha"];
[mutableSet addObject:@"wowo"];
[mutableSet addObject:@"nana"];
NSLog(@"mutableSet是:%@",mutableSet);

   3.3.删除元素

[mutableSet removeObject:@"hahha"];
NSLog(@"mutableSet是:%@",mutableSet);

 3.4.将一个集合中的元素添加到另外一个集合中(将两个几个连接起来生成一个大的集合)

[mutableSet unionSet:set1];
NSLog(@"mutableSet是:%@",mutableSet);

   3.5.在一个集合中,将另一个集合中包含的元素删除

[mutableSet minusSet:set];
NSLog(@"mutableSet是:%@",mutableSet);

4.索引集合

NSIndexSet * indexSet = [[[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(2, 2)]autorelease];
NSArray * newArray = [array objectsAtIndexes:indexSet];
NSLog(@"通过索引集合生成的数组是:%@",newArray);

  

原文地址:https://www.cnblogs.com/zwhFighting/p/4553344.html