iOS基础(十) - 集合(NSArray, NSDictionary, NSSet)

数组和字典,在iOS开发的时候经常用到,set则比较少用,所以,想搞明白它们的区别和使用情况。

1.NSArray和NSMutableArray

Accessing Indexes and Easily Enumerating Elements: Arrays
Arrays (such as NSArray and NSMutableArray) are ordered collections which allow indexed access to their contents.
You might use an array to store the information to be presented in a table view because the order matters.```
数组是分配的一块有顺序的内存空间,在Object-C里面只能存对象,不能存储基本数据类型。NSArray是不可变数组,一旦内存分配完成,不能添加,删除,替代里面的元素;相对于,NSMutableArray则可以添加,删除,替代里面的元素。
An NSArray object manages an immutable array—that is, after you have created the array, you cannot add, remove, or replace objects.
You can, however, modify individual elements themselves (if they support modification).
The mutability of the collection does not affect the mutability of the objects inside the collection.
You should use an immutable array if the array rarely changes, or changes wholesale.

数组是有序的集合,通过下标访问数组元素,可以储存多个相同的对象,代码如下:

ClassA *a = [ClassA new];
NSArray *array = @[a, a, a, a];
for (ClassA *item in array) {
      NSLog(@"%@", item);
}

2017-04-10 09:43:03.299452+0800 BasicTest[45405:3779278] 
2017-04-10 09:43:03.299481+0800 BasicTest[45405:3779278] 
2017-04-10 09:43:03.299491+0800 BasicTest[45405:3779278] 
2017-04-10 09:43:03.299500+0800 BasicTest[45405:3779278] 

数组元素方便通过下标访问可以快速遍历,但是,查找某一个元素需要遍历整个数组,也就是说,数组查找具体某一个元素效率很低。

2.NSDictionary和NSMutableDictionary

Associating Data with Arbitrary Keys: Dictionaries
Dictionaries (such as NSDictionary and NSMutableDictionary) are unordered collections that allow keyed-value access to their contents.
They also allow for fast insertion and deletion operations. Dictionaries are useful for storing values that have meaning based on their key.
For example, you might have a dictionary of information about California, with capital as a key and Sacramento as the corresponding value.
字典是一个无序的键-值对集合,每个键都是唯一的,同一个对象可以存在不同的键中,可以快速插入数据和删除数据。

3.NSSet和NSMutableSet

Offering Fast Insertion, Deletion, and Membership Checks: Sets
Sets (such as NSSet , NSMutableSet, and NSCountedSet) are unordered collections of objects.
Sets allow for fast insertion and deletion operations.
They also allow you to quickly see whether an object is in a collection.
NSSet and NSMutableSet store collections of distinct objects, while NSCountedSetstores a collection of non-distinct objects.
For example, suppose you have a number of city objects and you want to visit each one only once.
If you store each city that you visit in a set, you can quickly and easily see whether you have visited it.
集合相比于字典,除了可以快速插入,删除之外,还能快速判断一个对象是否在集合中,因为集合的实现使用了哈希算法。集合储存的对象是唯一的,不会相同,所以,无论加进去多少个一样的对象,集合里面永远只会有一个对象。如果不在意数组的顺序,可以用集合代替。

题外话:
NSIndexSet和NSIndexPath也挺有意思的,一个是下标的集合,一个是下标的路径,有兴趣的可以去看一下。

总结:

1.简单的存储一组数据,使用数组
2.存储的数据有关联的key,使用字典
3.如果不关心下标,有序和关联key,使用集合
4.数组在内存中是连续的,字典和集合都是不连续的;数组是有序的,字典和集合是无序的;数组可以通过下标访问,字典可以通过key访问,集合只能通过对象。

你可能感兴趣的:(iOS基础(十) - 集合(NSArray, NSDictionary, NSSet))