I think I understand the strong and weak keywords well, but I don’t understand how it is used in the code below. This code from SDWebImage by Olivier Poitrey is available on github. I understand the strong and weak keywords as described here: Explanation of strong and weak storage in iOS5
The code below uses the words __weak and __strong in a way that I'm curious. This is not a relationship between parents and parents, as I am used to seeing the weak used. However, I'm sure this is a template that is used often, as I saw it before in other code. It sets the __weak link before a block that runs on another thread. Then, inside the block, it establishes a weak link to a strong link.
I'm sure this is nice and elegant code, so I'm trying to figure it out. If the self ceases to exist before the block starts, weak self-regulation will be zero. When the block is running, the strong link will also be set to zero. Therefore, he will know to kill the rest of the operation, since the self no longer exists. Did I understand correctly?
Now, what happens if we do not use the words __weak and __strong? What if we only checked inside the block, regardless of whether it is on its own. The self will never become nothing, since the block copies the whole tree?
Can someone help demystify this amazing piece of code? Can someone confirm or reject my hypotheses?
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock;
{
[self cancelCurrentImageLoad];
self.image = placeholder;
if (url)
{
__weak UIImageView *wself = self;
id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
__strong UIImageView *sself = wself;
if (!sself) return;
if (image)
{
sself.image = image;
[sself setNeedsLayout];
}
if (completedBlock && finished)
{
completedBlock(image, error, cacheType);
}
}];
objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}