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

给你一囗甜甜゛ 提交于 2019-11-27 22:23:01

Try a combination of the 2nd and 3rd.

__weak id weakSelf = self;
[tapBlockView setTapBlock:^(UIImage* image) {
    [weakSelf.myImageArray addObject:image];
}

After maddy's answer - this is from 2012 WWDC lecture on GCD and asynchronous programming:

__weak MyClass *weakSelf = self;

[tapBlockView setTapBlock:^(UIImage* image) {
    __strong MyClass *strongSelf = weakSelf;
    if(strongSelf) {
        [strongSelf.myImageArray addObject:image];
    }
}];

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.

Your second and third ones appear correct. The second one works because you did not create a copy of the array, so that still points to the original one. The third one works because the reference to self is weak.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!