0

When I reading SDWebImage source code, I found a snippet

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.

Danyun Liu
  • 3,072
  • 24
  • 22
  • Why not use self directly ? – Danyun Liu Mar 27 '14 at 07:06
  • 1
    @Danyun `self` is an strong but it is out of the block scope, so the block will retain it. `sself` is strong but it is in the block scope, it will be released at the end of the block, so no circle. – KudoCC Mar 27 '14 at 07:57
  • @KudoCC It sound reasonable. I will accept it if you post your comment as an answer. – Danyun Liu Mar 27 '14 at 08:04

1 Answers1

1

self is an strong but it is out of the block scope, so the block will retain it. sself is strong but it is in the block scope, it will be released at the end of the block, so no circle.

BTW the correct answer of this question is a good explanation about the block circle.

Community
  • 1
  • 1
KudoCC
  • 6,912
  • 1
  • 24
  • 53