Search code examples
iosobjective-cblockretainweak

Retain Cycle on Class Methods Blocks


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!


Solution

  • 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.