美文网首页
NSSet介绍

NSSet介绍

作者: 白水灬煮一切 | 来源:发表于2019-03-11 11:06 被阅读0次

    NSSet、NSMutableSet

      NSSet和NSArray功能性质一样,用于存储对象,属于集合;只能添加cocoa对象,基本数据类型需要装箱。 NSSet 、 NSMutableSet是无序的集合,在内存中存储方式是不连续的,而NSArray是有序集合,在内存中存储位置是连续的。 

    NSSet和我们常用NSArry区别是:在搜索一个元素时NSSet比NSArray效率高,主要是它用到了一个算法hash(哈希)。比如你要存储元素A,一个hash算法直接就能直接找到A应该存储的位置;同样,当你要访问A时,一个hash过程就能找到A存储的位置。而对于NSArray,若想知道A到底在不在数组中,则需要便利整个数组,显然效率较低了;

    1NSSet *set= [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];2[setcount];//返回集合中对象的个数判断集合中是否拥有某个元素1//判断集合中是否拥有@“two”2BOOL ret = [setcontainsObject:@"two"];

    判断两个集合是否相等

    1NSSet * set2 = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];2//判断两个集合是否相等3BOOL ret = [setisEqualToSet:set2];

    判断set是否是set2的子集合

    1NSSet * set2 = [[NSSet alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five", nil];2//判断set是否是set2的子集合3BOOL ret = [set isSubsetOfSet:set2];

    集合也可以用枚举器来遍历1//集合也可以用枚举器来遍历2NSEnumerator * enumerator = [set objectEnumerator];3NSString *str;4while(str = [enumerator nextObject]) {5    ……6}

    通过数组来初始化集合(数组转换为集合)

    1NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];2NSSet *set=[[NSSet alloc] initWithArray:array];

    集合转换为数组

    1NSArray * array2 = [set allObjects];2、可变集合NSMutableSet1//可变集合NSMutableSet2NSMutableSet *set= [[NSMutableSet alloc] init];3[setaddObject:@"one"];4[setaddObject:@"two"];5[setaddObject:@"two"];//如果添加的元素有重复,实际只保留一个//删除元素2[setremoveObject:@"two"];3[setremoveAllObjects];

    将set2中的元素添加到set中来,如果有重复,只保留一个

    1//将set2中的元素添加到set中来,如果有重复,只保留一个2NSSet * set2 = [[NSSet alloc] initWithObjects:@"two",@"three",@"four", nil];3[setunionSet:set2];

    删除set中与set2相同的元素

    1[set minusSet:set2];

    3、指数集合(索引集合)NSIndexSet1//指数集合(索引集合)NSIndexSet2NSIndexSet * indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1,3)];//集合中的数字是123

    根据集合提取数组中指定位置的元素1//根据集合提取数组中指定位置的元素2NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];3NSArray * newArray = [array objectsAtIndexes:indexSet];//返回@"two",@"three",@"four"4、可变指数集合NSMutableIndexSet1NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];2[indexSet addIndex:0]3[indexSet addIndex:3];4[indexSet addIndex:5];5//通过集合获取数组中指定的元素6NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six", nil];7NSArray *newArray = [array objectsAtIndexes:indexSet];//返回@"one",@"four",@"six"

    相关文章

      网友评论

          本文标题:NSSet介绍

          本文链接:https://www.haomeiwen.com/subject/boevpqtx.html