سؤال

How can one create a dictionary of objects with weak references -- that is, the dictionary does not retain its keys and values -- on OS X 10.7 with ARC enabled? NSMapTable looks promising but unfortunately it doesn't use weak references when ARC is enabled.

هل كانت مفيدة؟

المحلول

NSMapTable is indeed what you want.

10.8+:

specifically in your case it sounds like you want to use this:

+ (id)weakToWeakObjectsMapTable
Return Value
A new map table object which has weak references to the keys and values.

from the docs:

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.

you can use either the shortcut class methods + (id)weakToWeakObjectsMapTable or + (id)weakToStrongObjectsMapTable depending on your needs.

also see NSMapTableOptions to see how to specify behavior to the other initializers.

NSMapTableWeakMemory
Uses weak read and write barriers appropriate for ARC or GC. Using NSPointerFunctionsWeakMemory object references will turn to NULL on last release. Equal to NSMapTableZeroingWeakMemory.

10.7+:

use – initWithKeyOptions:valueOptions:capacity: and pass NSMapTableZeroingWeakMemory in the options (assuming your objects are "weak-reference-safe") alternatively you can use – initWithKeyPointerFunctions:valuePointerFunctions:capacity: and specify custom functions if none of the built in ones work for you / arent available on you version. (maybe one of the "opaque" personalities would work for you)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top