一、NSSet
1> NSSet是一组单值对象的不可变集合,集合中元素没有顺序;
2> 操作包括:搜索、添加、删除集合中的元素(仅用于可变集合)、比较两个集合,计算两个集合的交集和并集等。
3> 常用方法:
使用一系列对象创建新集合:
+ (instancetype)setWithObjects:obj1, obj2, ..., nil;
使用一系列对象初始化新分配的集合:
- (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
确定集合是否包含anObject对象:
- (BOOL)containsObject:(id)anObject;
使用member:方法确定集合是否包含object对象:
- (id)member:(id)object;
为集合中的所有对象返回一个NSEnumerato对象:
- (NSEnumerator *)objectEnumerator;
确定receiver的每个元素是否都出现在otherSet中:
- (BOOL)isSubsetOfSet:(NSSet *)otherSet;
确定是否receiver中至少一个元素出现在对象otherSet中:
- (BOOL)intersectsSet:(NSSet *)otherSet;
确定两个集合是否相等:
- (BOOL)isEqualToSet:(NSSet *)otherSet;
二、NSMutableSet
1> NSMutableSet是NSSet的子类,是可变集合;
2> 常用方法:
创建新集合,使其具有存储numItems个元素的初始空间:
+ (instancetype)setWithCapacity:(NSUInteger)numItems;
将新分配的集合设置为numItems个元素的存储空间:
- (instancetype)initWithCapacity:(NSUInteger)numItems;
将对象object添加到集合中:
- (void)addObject:(id)object;
从集合中删除对象:
- (void)removeObject:(id)object;
删除集合中所有对象:
- (void)removeAllObjects;
将对象otherSet的所有元素添加到接收者:
- (void)unionSet:(NSSet *)otherSet;
从接收者中删除otherSet的左右元素:
- (void)minusSet:(NSSet *)otherSet;
从接受者中的所有不属于otherSet的元素删除:
- (void)intersectSet:(NSSet *)otherSet;
三、NSArray和NSSet的对比:
1> 共同点:
都是集合;
都能存放多个OC对象;
只能存放OC对象,不能存放非OC对象类型(基本数据类型)。
2> 不同点:
NSArray有顺序;
NSSet没有顺序。