iOS NSMapTable

首先我們?nèi)タ聪鹿俜轿臋n關(guān)于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,當(dāng)key、value在被釋放的時候,會自動從NSMapTable中移除這一項。NSMapTable中可以包含任意指針,使用指針去做檢查操作。

2.對于NSDictionary 中通常都是簡單key來對于一個object,而在NSMapTable中,不但可以使用key-object這樣的對應(yīng),還可以使用object-object這種對應(yīng)方式。

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.簡單使用,創(chuàng)建一個weak-weak的NSMapTable來存放映射對象,map中的對象的引用計數(shù)不會增加,當(dāng)其中的對象在別的釋放了的時候,也自動從這個map中消失。

可以通過這種方式來實現(xiàn)一個弱引用的字典。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容