05 OC之 集合 Set的使用

这篇博客详细介绍了Objective-C中NSSet和NSMutableSet的使用,包括创建集合、从数组初始化、获取元素个数、检查对象是否存在、集合操作如并集、交集、差集以及清除所有对象等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

*********************** 不可变集合 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 重置集合并将集合 set1mSet3.   
  •     [mSet3 setSet:set1];
  •     *[mSet3 setSet:mSet2];//在此之前 mSet2 已被清空。该行执行后,mSet3 = {()} 空集合
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值