在这个闭包中我需要 [unowned self] 还是 [weak self]?
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
}
}
我对为什么需要使用 [unowned self] 有点困惑。根据 this answer,如果 我不关心调用闭包时 self 是否还在附近,我应该只使用 [unowned self]。但我从来不明白为什么会这样。为什么我 不 关心自己是否在身边?我希望在调用闭包时 self 在附近——这就是我在那里编写代码的原因。
我需要在 animations
闭包中使用 unowned self 吗?
在这种情况下你不需要使用捕获列表,因为两个闭包都是UIView
并且没有被self
保留。您的示例中未创建保留周期。
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,如果 我不关心调用闭包时 self 是否还在附近,我应该只使用 [unowned self]。但我从来不明白为什么会这样。为什么我 不 关心自己是否在身边?我希望在调用闭包时 self 在附近——这就是我在那里编写代码的原因。
我需要在 animations
闭包中使用 unowned self 吗?
在这种情况下你不需要使用捕获列表,因为两个闭包都是UIView
并且没有被self
保留。您的示例中未创建保留周期。