Collections of zeroing weak references under ARC

前端 未结 8 658
粉色の甜心
粉色の甜心 2020-12-23 14:05

How can I get an array of zeroing weak references under ARC? I don\'t want the array to retain the objects. And I\'d like the array elements either to remov

8条回答
  •  不思量自难忘°
    2020-12-23 14:50

    If you are working with at least MacOS X 10.5, or iOS6, then:

    • NSPointerArray weakObjectsPointerArray/pointerArrayWithWeakObjects is a weak reference standin for NSArray
    • NSHashTable hashTableWithWeakObjects/weakObjectsHashTable is a weak reference standin for NSSet
    • NSMapTable is a weak reference standin for NSDictionary (can have weak keys and/or weak values)

    Note that the collections may not immediately notice that objects have gone away, so counts could still be higher, and keys could still exist even though the associated object is gone, etc. NSPointerArray has a -compact method which should in theory get rid of any nilled pointers. NSMapTable docs note that the keys for weakToStrong maps will remain in the table (even though effectively nil) until it is resized, meaning the strong object pointers can remain in memory even if no longer logically referenced.

    Edit: I see the original poster asked about ARC. I think it was indeed 10.8 and iOS 6 before those containers could be used with ARC -- the previous "weak" stuff was for GC, I think. ARC wasn't supported until 10.7, so it's really a question if you need to support that release and not 10.6, in which case you would need to roll your own (or perhaps use custom functions with NSPointerFunctions, which can then in turn be used with NSPointerArray, NSHashTable, and NSMapTable).

提交回复
热议问题