iOS NSMapTable

首先我们去看下官方文档关于NSMapTable中的说明

NSMapTable官方文档

1.在官方文档中的声明

The NSMapTable class is a mutable collection modeled after NSDictionary, with the following differences:

The major option is to have keys and/or values held “weakly” in a manner that entries are removed when one of the objects is reclaimed.

Its keys or values may be copied on input or may use pointer identity for equality and hashing.

It can contain arbitrary pointers (its contents are not constrained to being objects).

You can configure an NSMapTable instance to operate on arbitrary pointers and not just objects, although typically you are encouraged to use the C function API for void * pointers. (See Managing Map Tables for more information) The object-based API (such as setObject:forKey:) will not work for non-object pointers without type-casting.

这段话的大概意思就是说,

相对于NSDictionary 而言,NSMapTable 中的key-value是可以指定为weak、strong、copy的。

如果使用的是weak,当key、value在被释放的时候,会自动从NSMapTable中移除这一项。NSMapTable中可以包含任意指针,使用指针去做检查操作。

2.对于NSDictionary 中通常都是简单key来对于一个object,而在NSMapTable中,不但可以使用key-object这样的对应,还可以使用object-object这种对应方式。

3.通过官方文档中可以看到NSMapTable中有这么几种初始化方法

-initWithKeyOptions:valueOptions:capacity:

Returns a map table, initialized with the given options.

+mapTableWithKeyOptions:valueOptions:

Returns a new map table, initialized with the given options

-initWithKeyPointerFunctions:valuePointerFunctions:capacity:

Returns a map table, initialized with the given functions.

+strongToStrongObjectsMapTable

Returns a new map table object which has strong references to the keys and values.

+weakToStrongObjectsMapTable

Returns a new map table object which has weak references to the keys and strong references to the values.

+strongToWeakObjectsMapTable

Returns a new map table object which has strong references to the keys and weak references to the values.

+weakToWeakObjectsMapTable

Returns a new map table object which has weak references to the keys and values.

4.简单使用,创建一个weak-weak的NSMapTable来存放映射对象,map中的对象的引用计数不会增加,当其中的对象在别的释放了的时候,也自动从这个map中消失。

可以通过这种方式来实现一个弱引用的字典。

你可能感兴趣的:(iOS NSMapTable)