您的位置:首页 > 移动开发 > Objective-C

05 OC之 集合 Set的使用

2016-07-20 12:25 447 查看
***********************
不可变集合
Immutable Set***********************

   
1、创建对象集合set
  NSSet *set1 = [[NSSet
alloc]
initWithObjects:str1,str2, nil];

    NSArray *array = [NSArray
arrayWithObjects:str1,str2,@"zzxczv",
nil];
2、将数组
放到集合

  NSSet *set3 = [NSSet
setWithArray:array];
3、将集合转换为数组
  NSArray *array1 = [set3
allObjects];
4、集合中元素个数
  NSLog(@"集合中元素个数set3.count =
%ld",[set3 count]);   
5、从集合中获取某元素,不能保证随机
  NSString *str3 = [set3
anyObject];
6、集合中
没有
重复元素
  NSSet *set4 = [NSSet
setWithObjects:str1,str1,str2,str2,
nil];
7、将一个集合
赋给
另一个集合
  NSSet *set5 = [[NSSet
alloc]
initWithSet:set4];
8、两集合相加
  NSSet *set6 = [set5
setByAddingObjectsFromSet:set3];

    NSLog(@"set5 = %@",set5);   //不变

    

************************* 可变集合Mutable Set *************************

   
1、可变集合的创建

    NSMutableSet *mSet1 = [[NSMutableSet
alloc]
initWithCapacity:2];

    NSString *str7 =
@"What do you want?";

2、将数组str7放入集合mSet1

    [mSet1
addObject:str7];

3、类方法

    NSMutableSet *mSet2 = [NSMutableSet
setWithObjects:str1,str2,mSet1,
nil];    

4、移除一个元素  removeObject

    [mSet2
removeObject:@"qwertyuiop"];    

5、并集

    [mSet2
unionSet:set1];    

    

6、 取交集

//Removes from the receiving set each object that isn’t a member of another given set.

    [mSet2
intersectSet:set1];

7、删除所有元素

    [mSet2
removeAllObjects];    

    NSMutableSet *mSet3 = [[NSMutableSet
alloc]
initWithCapacity:3];

8、用 set 重置集合并将集合
set1 给 mSet3.   

    [mSet3
setSet:set1];

    *[mSet3 setSet:mSet2];//在此之前 mSet2 已被清空。该行执行后,mSet3 = {()} 空集合
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息