6 Replies
      Latest reply: Jan 4, 2017 5:31 AM by mark123499 RSS
      mark123499 Level 1 Level 1 (0 points)

        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

        • Re: NSTimer cause memory leak
          eskimo Apple Staff Apple Staff (6,765 points)

          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"

          • Re: NSTimer cause memory leak
            ksigiscar@cmc Level 2 Level 2 (75 points)

            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.

            • Re: NSTimer cause memory leak
              mark123499 Level 1 Level 1 (0 points)

              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.