Schedule timer causes memory leak

There is a memory leak issue in Timer if we use selector parameter.

self.myTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(myTimerAction), userInfo: nil, repeats: true)

If you use above code, the self will be a strong reference to target until the timer is invalidated, and we usually put timer as a private var in the class, so it’s a critical trap if we forget to stop timer before the object release.

We need to change the code and use block in timer, make an updateTimer() func and call it in the timer’s block.

        weak var weakSelf = self
        timer = Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true, block: { _ in
            weakSelf?.updateTimer()
        })

This code will solve the memory leak because it’s using weak self, then we can stop timer in deinit()

    deinit {
        timer?.invalidate()
    }
    

Leave a Reply

Your email address will not be published. Required fields are marked *