简体   繁体   English

将弱变量分配给强变量时

[英]When assign a weak variable to a strong variable

When I reading SDWebImage source code, I found a snippet 当我阅读SDWebImage源代码时,我发现了一个片段

if (url)
{
    __weak UIButton *wself = self;
    id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
    {
        __strong UIButton *sself = wself;
        if (!sself) return;
        if (image)
        {
            [sself setBackgroundImage:image forState:state];
        }
        if (completedBlock && finished)
        {
            completedBlock(image, error, cacheType);
        }
    }];
    objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

It is easy to understand that for avoiding the retain cycle, it uses __weak keyword for the self, however, why it assigns wself to a strong variable sself, won't the block be still retain the self. 很容易理解,为了避免保留周期,它为自己使用了__weak关键字,但是,为什么将wself分配给一个强大的变量self,所以它不会仍然保留自己。

self is an strong but it is out of the block scope, so the block will retain it. self是强者,但它不在区块范围内,因此区块将保留它。 sself is strong but it is in the block scope, it will be released at the end of the block, so no circle. sself很强,但是它在块范围内,它将在块的末尾释放,因此没有圈。

BTW the correct answer of this question is a good explanation about the block circle. 顺便说一句,这个问题的正确答案是关于圆弧的一个很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM