美文网首页iOS开发iOS底层基础知识
NSSet、NSMutableSet基本用法

NSSet、NSMutableSet基本用法

作者: MacShare | 来源:发表于2016-07-25 03:23 被阅读374次

NSSet、NSMutableSet基本用法

在Foundation框架中,提供了NSSet类,它是一组单值对象的集合,且NSSet实例中元素是无序,同一个对象只能保存一个。

一.不可变集合NSSet

1.NSSet的初始化

创建一个集合

NSSet *set1 = [[NSSet alloc] initWithObjects:@"one", @"two", nil];

通过数组的构建集合

NSArray *array = [NSArrayWithObjects:@"1", @"2", @"3", nil];

NSSet *set2 = [[NSSet alloc] initWithArray:array];

通过已有集合构建集合

NSSet *set3 = [[NSSet alloc] initWithSet:set2];

2.NSSet常用方法

集合中对象的个数

int count = [set3 count];

以数组的形式返回集合中所有的对象

NSArray *allObjects = [set3 allObjects];

返回集合中的任意一个对象

id object = [set3 anyObject];

判断两个集合的元素中有包含的对象,包含返回YES,否则为NO

BOOL isContain = [set4 containsObject:@"2"];

判断两个集合的元素是否有相等的对象,存在返回YES,否则为NO

BOOL isIntersect = [set4 intersectsSet:set2];

判断两个集合的元素是否完全匹配,匹配返回YES,否则为NO

BOOL isEqual = [set4 isEqualToSet:set5];

集合4是否是集合5的子集合,如果是返回YES,否则为NO

BOOL isSubset = [set4 isSubsetOfSet:set5];

创建一个新的集合2,集合2有两个对象

NSSet *set1 = [NSSet setWithObjects:@"a",nil];

NSSet *set2 = [set1 setByAddingObject:@"b"];

通过已有的两个集合,创建新的一个集合

NSSet *set7 = [NSSet setWithObjects:@"a",nil];

NSSet *set8 = [NSSet setWithObjects:@"z",nil];

NSSet *set9 = [set7 setByAddingObjectsFromSet:set8];

通过已有的集合和数组对象,创建一个新的集合

NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];

NSSet *set10 = [NSSet setWithObjects:@"z",nil];

NSSet *set11 = [set10 setByAddingObjectsFromArray:array];

二、可变集合NSMutableSet

常用方法

创建一个空的集合

NSMutableSet *set1 = [NSMutableSet set];

NSMutableSet *set2 = [NSMutableSet setWithObjects:@"1",@"2",nil];

NSMutableSet *set3 = [NSMutableSet setWithObjects:@"a",@"2",nil];

集合2减去集合3中的元素,集合2最后元素只有1个

[set2 minusSet:set3];

集合2与集合3中元素的交集,集合2最后元素只有1个

[set2 intersectSet:set3];

集合2与集合3中的元素的并集,集合2最后元素只有3个

[set2 unionSet:set3];

将空集合1设置为集合3中的内容

[set1 setSet:set3];

根据数组的内容删除集合中的对象

[set2 addObjectsFromArray:array];

[set2 removeObject:@"1"];

[set]2 removeAllObjects];

相关文章

  • NSSet、NSMutableSet基本用法

    NSSet、NSMutableSet基本用法 在Foundation框架中,提供了NSSet类,它是一组单值对象的...

  • iOS NSHashTable、NSMapTable、NSPoi

    NSHashTable 类似NSSet 、 NSMutableSet,与其区别在于NSSet 、 NSMutabl...

  • NSHashTable

    NSHashTable 是更广泛意义的NSSet,区别于NSSet / NSMutableSet,NSHashTa...

  • iOS array 与 set 的区别

    NSSet和NSArray都是对象容器,用于存储对象,属于集合; NSSet , NSMutableSet是无序...

  • NSSet NSArray NSHashTable

    NSArray和NSSet NSSet , NSMutableSet类声明编程接口对象,无序的集合,在内存中存储...

  • NSSet和NSMutableSet

    集合是无序的而不随机的,而且不会存在两个相同的元素,如果在设置的时候放入了两个相同的元素,系统会自动删掉一个元素;...

  • NSSet介绍

    NSSet、NSMutableSet NSSet和NSArray功能性质一样,用于存储对象,属于集合;只能添加co...

  • iOS中的NSHashTable和NSMapTable

    首先说NSHashTable: NSHashTable效仿了NSSet(NSMutableSet),但提供了比NS...

  • iOS NSSet 和 NSMutableSet

    今天在做项目的时候需要去除数组中的重复元素使用到了NSSet,对它并不熟悉,所以记录下来方便以后查找 set.al...

  • NSSet 和 NSMutableSet详解

    作者:孟令文 刚刚学习了Funcdation框架中的NSSet,跟大家分享一下。 1、集合:集合(NSSet)和数...

网友评论

    本文标题:NSSet、NSMutableSet基本用法

    本文链接:https://www.haomeiwen.com/subject/zksgjttx.html