如何在没有保留周期的情况下在块内保留强引用 [英] How to keep a strong reference inside of a block without having a retain cycle

查看:77
本文介绍了如何在没有保留周期的情况下在块内保留强引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在按钮上附加了一个块(使用此类别):

I have a block attached to a button (using this category):

__unsafe_unretained typeof(UIImage) *weakPic = originalPic;
[button addEventHandler:^{
    switch (state) {
    case state1:
        {
           UIViewController *vc = //some VC
           vc.pic = weakPic; // weakPic is nil at this point
                             // putting originalPic here would solve my problem
                             // but then I would have a retain cycle


        }  

    case state2:
        {
          // other stuff
        }
    }

}];

与按钮相关联的动作因状态而异.

the action associated with the button is different depending on the state.

这是问题所在:我必须保留以上__unsafe_unretained以避免保留周期.但是,此代码在originalPic = nil ..点处被调用,因此当我将weakPic分配给vc.pic时,我将其分配为nil值.如果我只用originalPic替换weakPic,那么它就可以正常工作.(originalPic将具有更新的值),但是我得到了保留周期.

Here is the problem: I must keep the above __unsafe_unretained to avoid having a retain cycle. However, this code is called at a point where originalPic = nil.. and so when I assign weakPic to vc.pic I'm assigning it a nil value. If I replace weakPic with just originalPic, then it works fine.. (originalPic will have the updated value) but then I get the retain cycle.. ideas?

推荐答案

在不了解代码的情况下,我建议您考虑声明一个weakSelf并在self上实现访问器.

Without knowing more about your code I suggest you consider declaring a weakSelf and implementing an accessor on self.

//the accessor
-(UIImage*)pic{
    return originalPic;
}

-(void)someSetupMethod{
    __weak id weakSelf = self;

    [button addEventHandler:^{
        switch (state) {
        case state1:
            {
               UIViewController *vc = //some VC
               vc.pic = [weakSelf pic]; // if weakself is nil at this point, then
                                        // originalPic is likely invalid


            }  

        case state2:
            {
              // other stuff
            }
        }

    }];
}

它可能不是您想要的弱自我,而是其他一些对象.在那种情况下,只要声明其他对象是弱的,只要您可以相对确定它会比按钮存在的时间长或长即可.

It may not be a weakSelf you want, but some other object. In that case just declare that other object to be weak, as long as you can be relatively sure it will exist as long or longer than the button.

这篇关于如何在没有保留周期的情况下在块内保留强引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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