使用块时避免保留周期的正确方法是什么 [英] What is the proper way to avoid Retain Cycle while using blocks

查看:151
本文介绍了使用块时避免保留周期的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NSMutableArray中添加由属性强定义的对象的正确方法是什么。

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

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

如果我要创建像

If I will create weak reference something like

__weak NSMutableArray *array = self.myImageArray;
[tapBlockView setTapBlock:^(UIImage* image) {
    [array addObject:image]; // If I will do this then how will I update original Array ?
}

我也试过

__weak id weakSelf = self;
[tapBlockView setTapBlock:^(UIImage* image) {
    [weakSelf storeImageInaNewMethod:image]; // Calling SToreImageInaNewMethod
}

-(void)storeImageInaNewMethod:(UIImage*)image {
   [self.myImageArray addObject:image]; // This again retaining cycle
}

更新原始对象的正确方法是什么按属性?

What is the proper way to update original object defined by property ?

推荐答案

尝试第2和第3组合。

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

这篇关于使用块时避免保留周期的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆