【问题标题】:Do I need [unowned self] or [weak self] in this closure?在这个闭包中我需要 [unowned self] 或 [weak self] 吗?
【发布时间】:2015-07-02 14:50:53
【问题描述】:
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(netHex: 0xfc3158)
    fadeBackground()
    NSTimer.scheduledTimerWithTimeInterval(self.fadeTime, target: self, selector: Selector("fadeBackground"), userInfo: nil, repeats: true)
}

func fadeBackground(){
    UIView.animateWithDuration(self.fadeTime, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
        var randomIndex = Int(arc4random_uniform(UInt32(CONSTANTS.MainColorScheme.count)))
        self.view.backgroundColor = CONSTANTS.MainColorScheme[randomIndex]
    }) { (stuff Bool) -> Void in
    }
}

我对为什么需要使用 [unowned self] 感到有些困惑。根据this answer,我应该只使用 [unowned self] 如果 我不关心调用闭包时 self 仍然存在。但我从来不明白为什么会这样。为什么我关心 self 是否在身边?当调用闭包时,我希望 self 存在——这就是我在那里编写代码的原因。

animations 闭包中是否需要 unowned self?

【问题讨论】:

    标签: ios swift memory-management


    【解决方案1】:

    在这种情况下,您不需要使用捕获列表,因为两个闭包都是UIView,而不是由self 保留。您的示例中未创建保留周期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2016-05-02
      • 2019-12-03
      • 2015-01-17
      • 2019-10-15
      • 2015-09-04
      相关资源
      最近更新 更多