#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
//1,初始化NSSet对象
NSSet *set = [NSSet setWithObjects:@"星期一",@"星期二", nil];
//2,member方法
#warning 重要的方法member 判断该集合是否含有某个对象,有则返回该对象,无则返回nil
id obj1 = [set member:@"星期一"];
id obj2 = [set member:@"星期三"];
NSLog(@"%@",obj1);
NSLog(@"%@",obj2);
//3,setByAddingObject:向集合中添加一个元素,返回添加后的新集合
set = [set setByAddingObject:@"星期三"];
set = [set setByAddingObject:@"星期四"];
NSLog(@"集合元素个数=%lu",(unsigned long)[set count]);//4
//4,setByAddingObjectsFromSet:将新集合加到旧集合中去,返回添加后的新集合
NSSet *otherSet = [NSSet setWithObjects:@"星期五",@"星期六", nil];
set = [set setByAddingObjectsFromSet:otherSet];
NSLog(@"集合元素个数=%lu",(unsigned long)[set count]);//6
//5,intersectsSet:两个集合是否有交集,有则返回YES,无则NO
BOOL isIntersects = [set intersectsSet:otherSet];
NSLog(@"%d",isIntersects);//1
//6,containsObject:集合中是否包含某元素,有则返回YES,无则返回NO
BOOL isContainsSunday = [set containsObject:@"星期日"];
BOOL isContainsSatday = [set containsObject:@"星期六"];
NSLog(@"set集合中是否含有星期天:%d",isContainsSunday);
NSLog(@"set集合中是否含有星期六:%d",isContainsSatday);
//7,anyObject:从集合中取出一个元素
NSLog(@"%@",[set anyObject]);
//8,isSubsetOfSet:判读某个集合是否是另外一个集合的子集
BOOL isSub = [otherSet isSubsetOfSet:set];
NSLog(@"%d",isSub);
//9,objectsPassingTest:过滤集合中的元素
set = [set setByAddingObject:@"今天天气很不错"];
NSLog(@"集合元素个数=%lu",(unsigned long)[set count]);//7
set = [set objectsPassingTest:^BOOL(id obj, BOOL *stop) {
//长度小于4的元素留下
return [obj length]<4;
}];
NSLog(@"集合元素个数=%lu",(unsigned long)[set count]);//6
//-------------------
//可变集合,可以添加,删除元素
//1,addObjectsFromArray:将数组中的元素添加到集合中去
NSMutableSet *mset = [NSMutableSet setWithObject:@"1"];
NSArray *arr = @[@"2",@"3",@"4"];
[mset addObjectsFromArray:arr];//@[@"1",@"2",@"3",@"4"];
NSLog(@"%lu",(unsigned long)[mset count]);//4
//2,removeObject:删除集合中某个元素
[mset removeObject:@"1"];//@[@"2",@"3",@"4"];
NSLog(@"%lu",(unsigned long)[mset count]);//3
NSMutableSet *otherMset = [NSMutableSet setWithObjects:@"4",@"5", nil];
//3,unionSet:计算两个集合的并集,直接改变mset
[mset unionSet:otherSet];
NSLog(@"%lu",(unsigned long)[mset count]);//5
//4,unionSet:计算两个集合的差集,直接改变mset
[mset minusSet:otherSet];
NSLog(@"%lu",(unsigned long)[mset count]);//3
//5,intersectsSet:计算两个集合的交集,直接改变mset
[mset intersectsSet:otherSet];
NSLog(@"%lu",(unsigned long)[mset count]);//3
return 0;
}
转载于:https://my.oschina.net/cgphp/blog/345155