在Foundation架構中,提供了一組單值對象的集合,且NSSet執行個體中的元素是無序的,同一個對象只能儲存一個,類似於java中的HashSet。感覺java和OC太像了
1、繼續不可變,NSSet
NSSet的建立類似於數組的建立,其實在Objective-c中NSSet和NSArray就很像,在後面會具體講他們之間的區別
NSSet *set1 = [NSSet setWithObjects:@"one",@"two",@"three" nil];//同樣nil不能少 //通過數組來建立 NSArray *array = [NSArray arrayWithObjects:@"hello",@"world",@"hao", nil]; NSSet *set2 = [NSSet setWithArray:array]; //通過已有集合構建 NSSet *set3 = [NSSet setWithSet:set2]; //集合中對象的個數 NSInteger *objNum = [set3 count]; //以數組的形式返回集合中的所有對象 NSArray *array1 = [set3 allObjects]; //看集合中是否包含某對象 BOOL isContain = [set3 containsObject:@"one"]; //集合set2是否是集合set3的子集合 BOOL isSub = [set2 isSubsetOfSet:set3]; //兩個集合是否相同 BOOL isEqual = [set3 isEqualToSet:set2]; //在原有集合的基礎上新加一個元素建立一個新集合 NSSet *set4 = [set3 setByAddingObject:@"yade"]; //把兩個集合合并成一個新的集合 NSSet *set5 =[set3 setByAddingObjectsFromSet:set2]; //把一個集合一個數組合并成一個新集合 NSSet *set6 = [set5 setByAddingObjectsFromArray:array];
2、可變集合NSMutableSet
繼承自NSSet
//首先還是建立兩個再說 NSMutableSet *mSet1 = [NSMutableSet setWithObjects:@"one",@"two",@"1", nil]; NSMutableSet *mSet2 = [NSMutableSet setWithObjects:@"three",@"four",@"1" nil]; //在mSet1中去除和mSet2中相同的元素,返回的是mSet2 [mSet2 minusSet:mSet1]; //獲得兩個集合的交集,返回的是mSet1 [mSet1 intersectSet:mSet2]; //取並集 [mSet1 unionSet:mSet2]; //將一個一個集合中的內容設定成另一個集合中的內容 [mSet1 setSet:mSet2]; //刪除對象 [mSet1 removeObject:@"one"]; //刪除所有 [mSet1 removeAllObjects];