我不知道如何在不使用计时器概念的情况下停止此调用。今天,当我试图描述项目时,我发现这个分配内存每次都会因为以下功能而增加:
func startAnimation(index: Int) {
UIView.animate(withDuration: 4.0, delay: 0.5, options:[UIViewAnimationOptions.allowUserInteraction, UIViewAnimationOptions.curveEaseInOut], animations: {
self.view.backgroundColor = self.colors[index]
}) { (finished) in
var currentIndex = index + 1
if currentIndex == self.colors.count { currentIndex = 0 }
self.startAnimation(index: currentIndex)
}
}
答案 0 :(得分:1)
做一件简单的事,提一个标志,
最初它应该,
var isViewDissappear = false
然后,
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isViewDissappear = true
}
然后在再次拨打电话时检查该标志,
func startAnimation(index: Int) {
UIView.animate(withDuration: 4.0, delay: 0.5, options:[UIViewAnimationOptions.allowUserInteraction, UIViewAnimationOptions.curveEaseInOut], animations: {
self.view.backgroundColor = self.colors[index]
}) { (finished) in
var currentIndex = index + 1
if currentIndex == self.colors.count { currentIndex = 0 }
if !self.isViewDissappear {
self.startAnimation(index: currentIndex)
}
}
}
就是这样。
答案 1 :(得分:0)
您通过捕获对动画闭包的self
的强引用来创建保留周期。这意味着您的self
由闭包拥有,而闭包由self
拥有 - 这会导致您提到的泄漏(内存使用量增加)。您可以通过使用捕获列表捕获弱对self
的引用来打破周期(阅读docs)。试试这个:
func startAnimation(index: Int) {
UIView.animate(withDuration: 4.0, delay: 0.5, options:[UIViewAnimationOptions.allowUserInteraction, UIViewAnimationOptions.curveEaseInOut], animations: { [weak self]
self?.view.backgroundColor = self?.colors[index]
}) { (finished) in
var currentIndex = index + 1
if currentIndex == self?.colors.count { currentIndex = 0 }
self?.startAnimation(index: currentIndex)
}
}