NSTimer cause memory leak

Hi all,


Could you tell me how can I prevent memory leak with NSTimer function?

I was coding iOS application in Swift 2.0.


Below my code:


import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "timer_action:", userInfo: nil, repeats: true)

}

func timer_action(timer: NSTimer) {

print("Hello")

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

When NSTimer's action called, memory leak is occured.

The code alloced 2MB in only 1.5 minutes.

I confirmed memory leak in Instruments and it shows 2MB value in "All Heap Allocations" field.


Thanks

Replies

Scheduling an NSTimer will create a retain loop between the run loop and the target of the timer. You break that retain loop by invalidating the timer.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thank you for your answer.


But, I know invalidating the timer may stop NSTimer.

How can I prevent memory leak without stopping the NSTimer?


Thank you.

I'm not reading anything here indicating that you have a real issue - like the 2MB could very well be a circular buffer used for the logging that takes place. So if you run this for an hour does it scale proportionally meaning that something like 80MB is allocated?

Alternatively, try and use Grand Central Dispatch to create the timer.


Use a weak reference to self in the closure executed by the timer to prevent a retain cycle.

This line:

NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "timer_action:", userInfo: nil, repeats: true)


Should be:

NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(timer_action), userInfo: nil, repeats: true)


You have to specify the selector correctly.


Unknown selectors can cause a memory leak.

I am terribly sorry that I made a big mistake that I thought "Total Bytes" indicated in Instruments meant amount of allocated memory.

I did not know that it contains released allocation memory.


I should have looked "Persistent Bytes".

During my longrun test, it did not increase proportionally (at most 3MB).


I apologize that I made you confused and wasted your time.

Thank you for helping me.