2017-04-12 20 views
1

我不知道如何在不使用計時器概念的情況下停止此通話。今天,試圖剖析我碰到這種分配內存附帶的項目時得到提高,因爲下面的函數的每一次:如何在轉到另一個視圖控制器時停止後臺調用?

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

回答

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

就是這樣。

+0

是的,我用同樣的方法。 – sharayu

0

你是通過捕獲強引用self到動畫關閉作出保留週期。這意味着您的self歸閉包所有,關閉歸self - 這會導致您提到的泄漏(增加內存使用量)。您可以通過使用捕獲列表(讀取docs)捕獲參考self來打破循環。試試這個:

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) 
    } 
} 
+0

嗨,我只是害怕停止呼叫,我正在使用ARC。 – sharayu

相關問題