简体   繁体   English

在此关闭过程中,我需要[无主的自我]还是[弱的自我]?

[英]Do I need [unowned self] or [weak self] in this closure?

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
    }
}

I'm a little confused about why I need to use [unowned self]. 我对为什么需要使用[无主的自我]感到有些困惑。 According to this answer , I should only use [unowned self] if I don't care that self is still around when the closure is called . 根据此答案 ,如果我不在乎在调用闭包时自身仍然存在,则仅应使用[unown self]。 But I never see why that would ever be the case. 但是我从来不明白为什么会这样。 Why would I not care if self is around? 为什么我关心,如果自己是在吗? I want self to be around when the closure is called -- that's why I wrote the code there. 调用闭包时,我希望self周围存在-这就是为什么我在此处编写代码的原因。

Do I need unowned self in the animations closure? animations关闭时是否需要无主的自我?

In this case you don't need to use capture list, because both closures are UIView and not retained by self . 在这种情况下,您不需要使用捕获列表,因为两个闭包都是UIView并且不由self保留。 The retain cycle is not created in your example. 在您的示例中未创建保留周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM