NSArray of weak references (__unsafe_unretained) to objects under ARC

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

    To add weak self reference to NSMutableArray, create a custom class with a weak property as given below.

    NSMutableArray *array = [NSMutableArray new];
    
    Step 1: create a custom class 
    
    @interface DelegateRef : NSObject
    
    @property(nonatomic, weak)id delegateWeakReference;
    
    @end
    
    Step 2: create a method to add self as weak reference to NSMutableArray. But here we add the DelegateRef object
    
    -(void)addWeakRef:(id)ref
    {
    
      DelegateRef *delRef = [DelegateRef new];
    
      [delRef setDelegateWeakReference:ref] 
    
      [array addObject:delRef];
    
    }
    

    Step 3: later on, if the property delegateWeakReference == nil, the object can be removed from the array

    The property will be nil, and the references will be deallocated at proper time independent of this array references

提交回复
热议问题