OC之NSSet/NSMutableSet

简介:

1、集合(NSSet)与数组(NSArray)比较:

(1)都是存储不同的对象的地址

(2)NSArray是有序的集合,NSSet是无序的集合。

(3)集合是一种哈希表,运用散列算法,查找集合中的元素比数组速度更快,但是它没有顺序。

2NSSet用法:

set集合:

NSSet * set= [[NSSet alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

set2集合:

NSSet * set2 = [[NSSet alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

1)返回集合中对象的个数

[set count];

2)判断集合中是否拥有某个元素

判断集合中是否拥有@”two”:

BOOL ret = [set containsObject:@"two"];

3)判断两个集合是否相等

BOOL ret = [set isEqualToSet:set2];

4)判断set是否是set2的子集合

BOOL ret = [set isSubsetOfSet:set2];

5)集合也可以用枚举器来遍历

NSEnumerator * enumerator = [set objectEnumerator];

NSString *str;

while(str =[enumerator nextObject])

{

……

}

6)数组转换为集合

NSArray * array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

 

NSSet * set= [[NSSet alloc] initWithArray:array];

7)集合转换为数组

NSArray * array2 = [set allObjects];

3、可变集合NSMutableSet

NSMutableSet用法:

NSMutableSet * set=[[NSMutableSet alloc] init];

1)添加元素

[setaddObject:@"one"];

[setaddObject:@"two"];

[setaddObject:@"two"];

如果添加的元素有重复,实际只保留一个删除元素

(1)删除元素

(a)删除指定元素:

[set removeObject:@"two"];

(b)删除所有元素:

[set removeAllObjects];

3)将set2中的元素添加到set

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

NSSet * set2 = [[NSSet alloc] initWithObjects:@"two",@"three",@"four", nil];

[set unionSet:set2];

4)删除set中与set2相同的元素

[set minusSet:set2];

4、指数集合(索引集合)NSIndexSet

NSIndexSet * indexSet = [[NSIndexSet alloc] initWithIndexesInRange:

NSMakeRange(1, 3)];

1)根据集合提取数组中指定位置的元素

NSArray * array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four", nil];

 

NSArray * newArray = [array objectsAtIndexes:indexSet];

返回@"two",@"three",@"four"

5、可变指数集合NSMutableIndexSet

NSMutableIndexSet *indexSet =[[NSMutableIndexSet alloc] init];

[indexSet addIndex:0]

[indexSet addIndex:3];

[indexSet addIndex:5];

通过集合获取数组中指定的元素

NSArray *array = [[NSArray alloc] initWithObjects:

@"one",@"two",@"three",@"four",@"five",@"six", nil];

 

NSArray *newArray = [array objectsAtIndexes:indexSet];

返回@"one"@"four"@"six"


目录
相关文章
|
Swift
(Swift&OC)UITextView的的使用技巧
(Swift&OC)UITextView的的使用技巧
90 0
|
存储 算法 程序员
iOS开发:NSSet的使用
在iOS开发过程中,有些时候会用到去重处理,也就是去掉重复的元素或者个数,然后再进行排序处理,这就使用到了集合(NSSet),它其实是一种哈希表,通过运用散列算法来查找集合中的元素。
323 1
iOS开发:NSSet的使用
|
XML 数据格式 iOS开发
|
索引 存储