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