【问题标题】:Do we need to use __weak self inside UIAnimationBlocks in ARC?我们需要在 ARC 的 UIAnimationBlocks 中使用 __weak self 吗?
【发布时间】:2015-04-21 11:20:53
【问题描述】:

我们是否需要在 UIAnimation 块中使用 __weak self ,如下所示?如果我们不将 self 指定为弱,是否会产生保留周期问题?

[UIView animateWithDuration:animationDuration 
                      delay:0 
                    options:UIViewAnimationCurveEaseInOut 
                 animations:^{
        [self doSomething];
    } completion:^(BOOL finished) {
        if (finished) {
            [self doSomething];
        }
    }];

我也对以下情况感到困惑。对此有什么想法吗?请分享您的 cmets。

[self.navController dismissViewControllerAnimated:animated 
                                       completion:^{
                                                      [self doSomething];
                                                  }];

我们应该在这里使用弱自我吗?

【问题讨论】:

  • 谢谢大家,我越来越清楚了。我也想讨论以下案例。 [self.navControllerdismissViewControllerAnimated:动画完成:^{ [self doSomething]; }];

标签: ios automatic-ref-counting objective-c-blocks retain-cycle


【解决方案1】:

这不是保留周期。保留周期是

self -> block -> self

在这种情况下,我们有

animation framework -> block
block -> self

第一个保留只是暂时的 - 当动画结束时块被释放。即使发生保留循环,它也只是暂时的,不会阻止对象释放。

【讨论】:

  • 下面的情况呢 void (^animateBlock)(void) = ^(void){ [self doSomething]; };
  • @arango_86 这与您在问题中所写的情况相同。要创建保留周期,您必须首先在对象上创建一个属性,例如@property (nonatomic, copy) void (^animateBlock)(void) 然后分配给它self.animationBlock = ^(void){ [self doSomething]; };
  • 在动画中使用弱 self 仍然很好,这样它就不会阻止视图控制器在视图控制器消失时被释放 - 并且在视图控制器时执行动画没有意义不再出现在视野中。
  • @Boon 如果视图不在层次结构中,则实际上不执行动画并立即调用回调。
  • @Sulthan 这样做并没有什么坏处,对吧?实际上,在 Swift 中,您会从动画块中获得一个弱自我。
【解决方案2】:

当可以保留循环时,您需要使用__weak。这不是这种情况,因为动画块不是自己保留的。

使用__weak 的另一种情况是在完成后将调用我们的块的长时间操作,并且可以在此操作期间释放self。例如,一些网络请求会在完成块中为我们的视图控制器调用接口更新。用户可以在请求期间退出我们的屏幕。在这种情况下不需要用块保留self,最好使用弱自我。但是使用动画块也不是这种情况。

【讨论】:

    【解决方案3】:

    不,它不会创建保留循环,因为块(闭包)未附加到 self
    欲了解更多信息,请查看 Apple 的Automatic Reference Counting

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多