简体   繁体   中英

NSTimer memory management in iOS 6

I have an NSTimer strong property in a view controler. I create and launch this timer by calling this method:

- (void)startTimer
{
   if (self.timer != nil) {
       [self.timer invalidate];
   }

   self.timer = [NSTimer scheduledTimerWithTimeInterval:10
                                                 target:self
                                               selector:@selector(timerDidFinish:)
                                               userInfo:nil
                                                repeats:NO];
}

Then, when timerDidFinish: is called, I call this method to stop the timer:

- (void)stopTimer
{
   if (self.timer != nil) {
       [self.timer invalidate];
       self.timer = nil;
   }
}

And after that, I perform some operations. At those operations end I call again startTimer . I need to do this to keep regularly performing the operations I need, and to always have the same time (10 secs) between operations.

In Instruments , using the Leaks template and navigating to the view controller that has this timer, I find that running in an iOS 7 device the Live Bytes value and the Allocations graph keep more or less constant along time:

iOS 7屏幕截图

But running in an iOS 6 device this same scenario, Live Bytes and Allocations graph steadily increase:

iOS 6屏幕截图

How can I handle this?

Thanks

You should try the heap shot analysis method to have further information about this possible leak. The method is pretty straightforward :

Start a debug session with instruments, and go to your viewController with the NSTimer property. Wait a little (more than 10 sec to have your timer finish at least once for example, or you can wait for more iterations if you know when the timer ends), then pop back to the previous view controller. In instruments, press "Mark Generation". You now have a instant representation of the memory at this time. Go back to your view controller, wait, pop it, create another generation, and repeat a few times.

You should end with a view like this one :

iOS堆生成

Each generation is represented by a red flag. The growth column represents memory allocation between two generation. If you don't leak, the Growth should be equals to 0 bytes within a few cycles. If not, you can see the detail of the growth by extending the generation, and see which objects were allocated between the generations. It should help you locating your issue.

For further information about Instruments, you should read this great tutorial : http://www.raywenderlich.com/23037/how-to-use-instruments-in-xcode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM