码迷,mamicode.com
首页 > 其他好文 > 详细

Objective-C----NSSet 、 NSMutableSet 、 NSCountedSet

时间:2015-06-20 10:35:35      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:objective   集合   set   mutableset   countedset   

直接上代码:

/*
         *  NSSet   不可变 集合
         *
         */

        // 两种初始化方式
        NSSet *set1 = [[NSSet alloc] initWithObjects:@"1", @"2", @"3", nil] ;
        NSLog( @"%@", set1 ) ;

        NSSet *set2 = [NSSet setWithObjects:@"12", @"23", @"34", nil] ;
        NSLog( @"%@", set2 ) ;

        //用数组对象来创建集合对象
        NSArray *array = @[@1, @2, @2] ;
        //initWithArray 和 setWithArray 将数组对象转换成集合对象,这样能将数组中重复的对象过滤掉
        NSSet *set3 = [[NSSet alloc] initWithArray:array] ;
        NSLog( @"%@", set3 ) ;
        NSSet *set4 = [NSSet setWithArray:array] ;
        NSLog( @"%@", set4 ) ;

        //获取集合中对象的个数
        NSLog( @"%ld", [set4 count] ) ;

        //获取集合中的对象(返回的是任意一个对象,如果集合中没有对象,则返回nil)
        id object1 = [set4 anyObject] ;
        NSLog( @"%@", object1 ) ;

        //判断一个给定的对象是否包含在指定的集合中
        NSString *result1 = [set4 containsObject:@2] ? @"YES" : @"NO" ;
        NSLog( @"%@ is contained int set %@", @2, result1 ) ;
//        @2  换成  @"2" 结果打印的是  NO
//        NSString *result1 = [set4 containsObject:@"2"] ? @"YES" : @"NO" ;
//        NSLog( @"%@ is contained int set %@", @"2", result1 ) ;

        /*
         *  NSMutableSet  可变 集合
         *
         */

        //初始化
        NSMutableSet *mutableSet1 = [[NSMutableSet alloc] init] ;
        NSLog( @"%@", mutableSet1 ) ;
        NSMutableSet *mutableSet2 = [NSMutableSet set] ;
        NSLog( @"%@", mutableSet2 ) ;
        //通过不可变对象创建
        NSMutableSet *mutableSet3 = [[NSMutableSet alloc] initWithSet:set1] ;
        NSLog( @"%@", mutableSet3 ) ;
        NSMutableSet *mutableSet4 = [NSMutableSet setWithSet: set1] ;
        NSLog( @"%@", mutableSet4 ) ;

        //添加集合元素(注意:@4 和 @"4"不一样)
        [mutableSet4 addObject:@4] ;
        NSLog( @"%@", mutableSet4 ) ;

        //删除单个集合元素
        [mutableSet4 removeObject:@4] ;
        NSLog( @"%@", mutableSet4 ) ;

        //删除所有集合元素
        [mutableSet4 removeAllObjects] ;
        NSLog( @"%@", mutableSet4 ) ;

        /*
         *   NSCountedSet 
         *
         *   是 NSSet的子类,能记录集合中的元素的重复次数
         */

        //
        NSCountedSet *countSet1 = [NSCountedSet set] ;
        [countSet1 addObject:@1] ;
        [countSet1 addObject:@2] ;
        [countSet1 addObject:@3] ;
        [countSet1 addObject:@2] ;
        NSLog( @"%@", countSet1 ) ;

        //单独获取某个对象在集合中出现过多少次
//        NSLog( @"%ld", [countSet1 countOfObjc:@3] ) ;
        NSLog( @"%ld", [countSet1 countForObject:@5] ) ;

Objective-C----NSSet 、 NSMutableSet 、 NSCountedSet

标签:objective   集合   set   mutableset   countedset   

原文地址:http://blog.csdn.net/zhengang007/article/details/46572143

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!