How to keep a strong reference inside of a block without having a retain cycle

一世执手 提交于 2019-12-23 02:19:06

问题


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.

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?


回答1:


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.




回答2:


You might also want to look at declaring it as a __block variable. The __block keyword prevents a copy of the object from being made inside the block.

See this thread for a better explanation of __weak and __block references.



来源:https://stackoverflow.com/questions/18831460/how-to-keep-a-strong-reference-inside-of-a-block-without-having-a-retain-cycle

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