What is the proper way to avoid Retain Cycle while using blocks

前端 未结 4 1775
有刺的猬
有刺的猬 2020-12-05 21:16

What is the proper way to add objects in NSMutableArray which is strongly defined by property.

[tapBlockView setTapBlock:^(UIImage* image) {
   [self.myImage         


        
4条回答
  •  春和景丽
    2020-12-05 21:38

    In your case you only need to reference an array which is referenced by self, so:

    NSMutableArray *array = self.myImageArray;
    [tapBlockView setTapBlock:^(UIImage* image)
                              {
                                 [array addObject:image]; // No cycle
                              }];
    

    Works fine provided that self.myImageArray does not return different array references at different times. There is no cycle: the current object references the array and the block, and in turn the block references the array.

    If self.myImageArray does return different array references as different times then use a weak reference to self, your case 3.

提交回复
热议问题