1
votes

I know that when we're using ARC and blocks, we should use __weak to prevent capturing strongly self and prevent a retain cycle ! But I was wondering if in the following example I need to use __weak ?

__weak MyViewController *weakSelf = self;
[self.personObject.gallery downloadLogoCompletionBlock:^(UIImage *image) {
                                        if (image) {
                                            weakSelf.logoImageView.image = image;
                                        }];

Gallery is retaining the block not self, right ? If so I could write :

self.logoImageView.image = image;

Thanks for your answers

3
Use __weak on which reference?trojanfoe
@trojanfoe oups sorry I just edited my answerSJ17
Yeah that looks reasonable to me, however given you are calling a method in self anyway, it might not be necessary.trojanfoe
Can you provide the implementation of the downloadLogoCompletionBlock: method? It will tell us if you are running into a retain cycle.Pedro Mancheno
You should create a strong reference to self inside your block and assign the weakReference to it.JonahGabriel

3 Answers

0
votes

With a strong reference self inside the block you would have a (temporary) retain cycle

self -> _personObject -> _gallery -> BLOCK -> self

assuming that the properties personObject, gallery are backed up by instance variables _personObject, _gallery. The retain cycle will be "destroyed" as soon as the completion block is called. If the completion block is never called then self can never be deallocated.

Therefore, if self should possibly be deallocated before the completion block is called, you should use a weak reference.

0
votes

This would cause an cycle, just longer than many.

self -> personObject -> gallery -> block
  ^---------------------------------|

However, this block will live only long enough to be called once, then the gallery should release it, breaking the cycle.

0
votes

It depends.

Lets say you pop this MyViewController instance from a navigation controller and you expect it to deallocate.

Assuming gallery holds a strong reference to the block, if you didn't use a weak reference you will run into a retain cycle.

personObject.gallery won't get deallocated, because your view controller didn't get deallocated either, since it is getting retained by personObject.gallery's block in the first place.

The other scenario is that gallery does not retain the block, in which case you won't run into the retain cycle.

If for some reason, you don't what goes on with the block inside the implementation of gallery, it's always a good idea to use a weak reference, just in case!