NSSet与NSMutableSet

本文深入探讨了Objective-C与Swift在iOS开发领域的应用与对比,包括其语法特点、优缺点及实际项目案例,旨在帮助开发者更好地选择和运用这两种语言。
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值