NSArray of weak references (__unsafe_unretained) to objects under ARC

前端 未结 12 744
南旧
南旧 2020-11-27 11:26

I need to store weak references to objects in an NSArray, in order to prevent retain cycles. I\'m not sure of the proper syntax to use. Is this the correct way?



        
12条回答
  •  误落风尘
    2020-11-27 12:11

    The solutions to use a NSValue helper or to create a collection (array, set, dict) object and disable its Retain/Release callbacks are both not 100% failsafe solutions with regard to using ARC.

    As various comments to these suggestions point out, such object references will not work like true weak refs:

    A "proper" weak property, as supported by ARC, has two behaviors:

    1. Doesn't hold a strong ref to the target object. That means that if the object has no strong references pointing to it, the object will be deallocated.
    2. If the ref'd object is deallocated, the weak reference will become nil.

    Now, while the above solutions will comply with behavior #1, they do not exhibit #2.

    To get behavior #2 as well, you have to declare your own helper class. It has just one weak property for holding your reference. You then add this helper object to the collection.

    Oh, and one more thing: iOS6 and OSX 10.8 supposedly offer a better solution:

    [NSHashTable weakObjectsHashTable]
    [NSPointerArray weakObjectsPointerArray]
    [NSPointerArray pointerArrayWithOptions:]
    

    These should give you containers that hold weak references (but note matt's comments below).

提交回复
热议问题