NSArray of weak references (__unsafe_unretained) to objects under ARC

前端 未结 12 719
南旧
南旧 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:15

    As Jason said, you can't make NSArray store weak references. The easiest way to implement Emile's suggestion of wrapping an object inside another object that stores a weak reference to it is the following:

    NSValue *value = [NSValue valueWithNonretainedObject:myObj];
    [array addObject:value];
    

    Another option: a category that makes NSMutableArray optionally store weak references.

    Note that these are "unsafe unretained" references, not self-zeroing weak references. If the array is still around after the objects are deallocated, you'll have a bunch of junk pointers.

提交回复
热议问题