集合的初始化以及操作方法和NSString、NSArray、NSDictionary等都很类似,很多方法写几遍就能了解意思并上手使用,不建议全部记忆。
//集合就是一组无序的元素,但里面元素不可重复
//集合也分为不变和可变
//不变集合
//初始化,直接复制、通过array传递或者通过已有的set传递等
NSSet *set1=[[NSSet alloc]initWithObjects:@"1",@"2",@"3", nil];
NSArray *arr1=[NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSSet *set2=[NSSet setWithArray:arr1];
NSSet *set3=[NSSet setWithSet:set1];
//高级初始化,就是从已有的集合+对象/集合/数组再生成一个新的
NSSet *set4=[set3 setByAddingObject:@"4"];//复制了set3并新增了一个对象
NSSet *set5=[set3 setByAddingObjectsFromSet:set1];
NSSet *set6=[set3 setByAddingObjectsFromArray:arr1];
//集合的一些方法
//集合个数
int count=[set3 count];
//把集合中元素变成数组赋值给新的数组
NSArray *arr2=[set3 allObjects];
//返回集合中任意,任意一个对象
id obj=[set3 anyObject];
//集合中是否包含某对象
BOOL test1=[set3 containsObject:@"1"];
//两个集合是否有相同对象
BOOL test2=[set3 intersectsSet:set2];
//两个集合是否相同
BOOL test3=[set3 isEqualToSet:set2];
//一个集合是否是另一个的子集
BOOL test4=[set3 isSubsetOfSet:set2];
//可变集合
//可变集合的初始化,大同小异
NSMutableSet *mset1=[NSMutableSet setWithObjects:@"1",@"2",@"3", nil];
NSMutableSet *mset2=[NSMutableSet setWithArray:arr1];
NSMutableSet *mset3=[NSMutableSet setWithSet:set1];
NSMutableSet *mset4=[NSMutableSet set];
//可变集合的一些方法
//从一个集合种减去一个集合
[mset3 minusSet:mset2];
//两个集合交集
[mset3 intersectsSet:mset2];
//两个集合并集
[mset3 unionSet:mset2];
//从数组中添加一个对象
[mset3 addObjectsFromArray:arr1];
//把一个数组设置为另一个数组的值
[mset3 setSet:mset2];
//删除所有对象
[mset3 removeAllObjects];
//根据名称删除特定对象
[mset3 removeObject:@"1"];