NSSet和NSMutableSet的常用方法

NSSet和NSMutableSet的常用方法

标签(空格分隔): 常用方法


一、NSSet的常用方法

  • 不可变集

1、创建

- (instancetype)initWithObjects:(ObjectType)firstObj, …

NSSet *set = [[NSSet alloc] initWithObjects:@"1",@"2",@"3", nil];
NSLog(@"set = %@",set);

运行结果

2016-02-27 14:48:37.805 OCLesson5_NSSet[1744:142587] set = {(
    1,
    2,
    3
)}

2、元素个数

NSLog(@"count = %ld",[set count]);

运行结果

2016-02-27 14:48:37.806 OCLesson5_NSSet[1744:142587] s1 = 1

3、将set中的所有元素放到数组中

@property (readonly, copy) NSArray *allObjects;

NSArray *setArr = [set allObjects];
NSLog(@"setArr = %@",setArr);

运行结果

2016-02-27 14:48:37.806 OCLesson5_NSSet[1744:142587] setArr = (
    1,
    2,
    3
)

4、任意取出一个元素

- (nullable ObjectType)anyObject

NSString *s1 = [set anyObject];
NSLog(@"s1 = %@",s1);

运行结果

2016-02-27 14:48:37.806 OCLesson5_NSSet[1744:142587] s1 = 1

5、判断集set中是否包含给定对象

- (BOOL)containsObject:(ObjectType)anObject;

BOOL b = [set containsObject:@"1"];
NSLog(@"b = %d",b);

运行结果

2016-02-27 14:48:37.806 OCLesson5_NSSet[1744:142587] b = 1

二、NSMutableSet

  • 可变集

1、创建

NSMutableSet *mset = [[NSMutableSet alloc] initWithCapacity:10];

2、添加元素

[mset addObject:@"1"];
[mset addObject:@"2"];
[mset addObject:@"3"];
NSLog(@"mset = %@",mset);

运行结果

2016-02-27 14:48:37.806 OCLesson5_NSSet[1744:142587] mset = {(
    3,
    1,
    2
)}

3、删除元素

[mset removeObject:@"2"];
NSLog(@"mset = %@",mset);

运行结果

2016-02-27 14:48:37.807 OCLesson5_NSSet[1744:142587] mset = {(
    3,
    1
)}

4、删除全部

[mset removeAllObjects];
NSLog(@"mset = %@",mset);

运行结果

2016-02-27 14:48:37.807 OCLesson5_NSSet[1744:142587] mset = {(
)}
Program ended with exit code: 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值