NSSet隘庄、NSMutableSet基本用法
在Foundation框架中,提供了NSSet類癣亚,它是一組單值對象的集合丑掺,且NSSet實例中元素是無序,同一個對象只能保存一個述雾。
一.不可變集合NSSet
1.NSSet的初始化
創(chuàng)建一個集合
NSSet *set1?=?[[NSSet alloc] initWithObjects:@"one",?@"two", nil];
通過數(shù)組的構建集合
NSArray *array?=?[NSArrayWithObjects:@"1",?@"2",?@"3", nil];
NSSet *set2?=?[[NSSet alloc] initWithArray:array];
通過已有集合構建集合
NSSet *set3?=?[[NSSet alloc] initWithSet:set2];
2.NSSet常用方法
集合中對象的個數(shù)
int count =?[set3 count];
以數(shù)組的形式返回集合中所有的對象
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];
創(chuàng)建一個新的集合2,集合2有兩個對象
NSSet *set1?=?[NSSet setWithObjects:@"a",nil];
NSSet *set2?=?[set1 setByAddingObject:@"b"];
通過已有的兩個集合斗忌,創(chuàng)建新的一個集合
NSSet *set7?=?[NSSet setWithObjects:@"a",nil];
NSSet *set8?=?[NSSet setWithObjects:@"z",nil];
NSSet *set9?=?[set7 setByAddingObjectsFromSet:set8];
通過已有的集合和數(shù)組對象质礼,創(chuàng)建一個新的集合
NSArray *array?=?[NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSSet *set10?=?[NSSet setWithObjects:@"z",nil];
NSSet *set11?=?[set10 setByAddingObjectsFromArray:array];
二、可變集合NSMutableSet
常用方法
創(chuàng)建一個空的集合
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];
根據(jù)數(shù)組的內容刪除集合中的對象
[set2 addObjectsFromArray:array];
[set2 removeObject:@"1"];
[set]2 removeAllObjects];