override func viewDidLoad() {
        super.viewDidLoad()
        fadeBackground()
        NSTimer.scheduledTimerWithTimeInterval(self.fadeTime, target: self, selector: Selector("fadeBackground"), userInfo: nil, repeats: true)
 }

func fadeBackground(){
    var spiralView: UIImageView?
    var subviews = self.view.subviews
    for v in subviews{
        if v.isKindOfClass(UIImageView){
            spiralView = v as? UIImageView
        }
    }
    UIView.animateWithDuration(self.fadeTime, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { [unowned self] () -> Void in
        var randomIndex = Int(arc4random_uniform(UInt32(CONSTANTS.MainColorScheme.count)))
        var randomIndex2 = Int(arc4random_uniform(UInt32(CONSTANTS.MainColorScheme.count)))
        self.view.backgroundColor = CONSTANTS.MainColorScheme[randomIndex]
        if spiralView != nil {
            spiralView!.tintColor = CONSTANTS.MainColorScheme[randomIndex2]
        }
    }) { (stuff Bool) -> Void in

    }
}

如您所见,我已经在封闭中添加了[unowned self]。我不确定为什么这个视图控制器仍然不调用deinit()。我猜那里仍然有内存泄漏?

我需要在viewDidDisappear上停止计时器吗?我怎么做?

最佳答案

解决了我的问题。

我必须使viewWillDisappear上的计时器无效。

var fader: NSTimer?
override func viewWillDisappear(animated: Bool) {
    println("lobby viewWillDisappear")
    super.viewWillDisappear(animated)
    self.fader!.invalidate()
    self.fader = nil
}

关于ios - 由于封闭强引用或NSTimer,我的Swift代码未调用deinit。我该如何解决?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29889764/

10-09 09:48