2

As far as I know when we work with blocks we must create a __weak instance of the object running the method with the code, and then a __strong one to keep the weak alive:

__weak __typeof(self) weakSelf = self;
[self setHandler:^{
     __strong __typeof(weakSelf) strongSelf = weakSelf;
     [strongSelf doSomething];
}];

Until here it's clear, if we called self from inside the block it would be retained by itself and never released. But my question is how to handle the same situation when the block is in a class method (rather than instance method), as for example in a UIView animation:

[UIView animateWithDuration:...
                      delay:...
                    options:...
                 animations:^{
                 // [self someMethod] or weak/strong reference to self [strongSelf someMethod]?
                         }
                 completion:^(BOOL finished) {
                 // [self someMethod] or weak/strong reference to self [strongSelf someMethod]?
                         }];

I've seen several examples using weak/strong reference to self in these cases, but since the completion isn't called from any instance it should retain self, am I missing something? Thanks!

Pablo A.
  • 2,042
  • 1
  • 17
  • 27

1 Answers1

4

You need to use weakSelf when your object (self) has a strong reference to the block and the blocks has a reference back to your object.

In the case of UIView class method you don't own - have reference to this block so you can use self in it without creating a retain cycle. This block will execute and then will be released.

stefos
  • 1,235
  • 1
  • 10
  • 18
  • Thanks stefos, I needed someone to confirm that! – Pablo A. Jun 24 '16 at 16:38
  • Just wondering, does it make sense to use a strong reference within the block in this case if you're not sure if the object is going to be released before calling the block? Would it be necessary to also use `weak` and `strong`of weak when doing so? – Pablo A. Jun 27 '16 at 08:04