Collections of zeroing weak references under ARC

2019-01-31 06:10发布

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 remove themselves when they're deallocated, or set those entries to nil.

Similarly, how can I do that with a dictionary? I don't want the dictionary to retain the values. And again, I'd like the dictionary elements either to remove themselves when the values are deallocated, or set the values to nil. (I need to retain the keys, which are the unique identifiers, at least until the corresponding values are deallocated.)

These two questions cover similar ground:

But neither is asking for zeroing references.

Per the documentation, neither NSPointerArray nor NSHashMap support weak references under ARC. NSValue's nonretainedObjectValue will not work either, as it is non-zeroing.

The only solution I see is to create my own NSValue-like wrapper class with a (weak) property, as this answer mentions, near the end. Is there a better way I'm not seeing?

I'm developing for OS X 10.7 and iOS 6.0.

8条回答
▲ chillily
2楼-- · 2019-01-31 06:37

I just create non-threadsafe weak ref version of NSMutableDictionary and NSMutableSet. Code here: https://gist.github.com/4492283

For NSMutableArray, things is more complicated because it cannot contain nil and an object may be added to the array multiple times. But it is feasible to implemented one.

查看更多
看我几分像从前
3楼-- · 2019-01-31 06:39

NSMapTable should work for you. Available in iOS 6.

查看更多
登录 后发表回答