在 Class 方法块上保留循环

Retain Cycle on Class Methods Blocks

据我所知,当我们使用块时,我们必须创建对象的 __weak 实例 运行 带有代码的方法,然后 __strong 一个要保留的活着的弱者:

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

到此为止很清楚,如果我们从块内部调用 self,它将自行保留并且永远不会释放。但是我的问题是当块在 class 方法(而不是实例方法)中时如何处理相同的情况,例如在 UIView 动画中:

[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]?
                         }];

我见过几个在这些情况下使用 weak/strong 引用 self 的例子,但由于完成不是从任何实例调用的,它应该保留 self,我是不是遗漏了什么?谢谢!

当您的对象 (self) 对块具有强引用并且块对您的对象有引用时,您需要使用 weakSelf。

对于您不拥有的 UIView class 方法 - 请参考此块,以便您可以在其中使用 self 而无需创建保留循环。此块将执行,然后将被释放。