Objective-C 集合

来源:互联网 发布:淘宝店铺淘字号 编辑:程序博客网 时间:2024/05/22 14:15

#import <Foundation/Foundation.h>


int main(int argc,const char * argv[])

{


    @autoreleasepool {

        

        // insert code here...

        

        //集合

        //类方法创建集合

        NSSet *set1 = [NSSetsetWithObjects:@"1",@"2",nil];

        //实例方法创建集合

        NSSet *set2 = [[NSSetalloc]initWithObjects:@"3",@"4",@"2",nil];

        //通过数组创建集合

        NSArray *array1 = [NSArrayarrayWithObjects:@"7",@"10" ,nil];

        //通过已有数组创建集合

        NSSet *set3 = [NSSetsetWithArray:array1];

        //通过已有集合创建集合

        NSSet *set4 =[NSSetsetWithSet:set1];

        NSLog(@"set1 : %@",set1);

        NSLog(@"set2 : %@",set2);

        NSLog(@"set3 : %@",set3);

        NSLog(@"set4 : %@",set4);

        

        

        

        //集合的常用方法

        //集合中对象的个数

        int count = [set2 count];

        NSLog(@"set2 :%d",count);

        

        //以数组形式返回集合中所有对象

        NSArray *objects = [set1 allObjects];

        NSLog(@"objects:%@",objects);

        

        //将集合3中任意一个对象

        id object = [set3 anyObject];

        NSLog(@"object :%@",object);

        

        //是否包含摸个元素

        BOOL isContain = [set4 containsObject:@"1"];

        NSLog(@"isContain :%d",isContain);

        

        //集合间是否存在交集

        BOOL isInsersect = [set1 intersectsSet:set2];

        NSLog(@"isInsersect:%d",isInsersect);

        

        //集合是否有匹配(集合间的各个元素都相同)

        BOOL isEqual = [set1 isEqual:set2];

        NSLog(@"isEqual:%d",isEqual);

        

        //集合是否是另一个集合的子集

        BOOL isSub = [set1 isSubsetOfSet:set2];

        NSLog(@"isSub:%d",isSub);

        

        

        //为集合追加元素

        NSSet *set5 = [NSSetsetWithObjects:@"one",nil];

        NSSet *appSet1 = [set5 setByAddingObject:@"two"];

        NSLog(@"appSet1:%@",appSet1);

        //用已有集合给新集合追加

        NSSet *appSet2 = [appSet1 setByAddingObjectsFromSet:set3];

        NSLog(@"appSet2:%@",appSet2);

        

        //把已有数组追加给集合

        NSArray *array2 = [NSArrayarrayWithObject:@"end"];

        NSSet *appSet3 = [set5 setByAddingObjectsFromArray:array2];

        NSLog(@"appSet3:%@",appSet3);

        

        //可变集合

        //创建一个空集合

        NSMutableSet *set6 = [NSMutableSetsetWithObjects:@"1",@"2",@"a",nil];

        

        NSMutableSet *set7 = [NSMutableSetsetWithObjects:@"1",@"3",@"a",nil];

        

        //集合相减

        [set6 minusSet:set7];

        NSLog(@"set6:%@",set6);

        

        //集合之间交集

        [set6 intersectsSet:set7];

        NSLog(@"set6:%@",set6);

        

        //集合之间并集

        [set6 unionSet:set7];

        NSLog(@"set6:%@",set6);

        

        //指定集合一个对象删除

        [set6 removeObject:@"2"];

         NSLog(@"set6:%@",set6);

    }

    return 0;

}


0 0
原创粉丝点击