Enable and disable the NSTimer timer in iOS, iosnstimer
I. Only call the timer method once:
// It is not repeated and is called only once. Timer stops running once
MyTimer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target: self selector: @ selector (function :) userInfo: nil repeats: NO];
Ii. Repeat the timer method:
// Run the function method every 2 seconds.
Timer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector: @ selector (function :) userInfo: nil repeats: YES];
Note: When the repeats of the counter is set to YES, the reference count of self is increased by 1. Therefore, self (viewController) may not be released. Therefore, you must stop the timer in the viewDidDisappear method. Otherwise, memory leakage may occur.
3. completely stop timer: (this is the permanent stop of timer. After the stop, you must leave the timer empty. Otherwise, the timer is not released, causing unnecessary memory overhead)
// Cancel the timer
[Timer invalidate];
Timer = nil;
4. Disable the timer when the page disappears, and enable the timer when the page is opened again.
// The page is about to enter the foreground and the timer is enabled
-(Void) viewWillAppear :( BOOL) animated
{
// Enable the timer
[Self. myTimer setFireDate: [NSDate distantPast]; // far away
}
// The page disappears. The page is not displayed in the background and the timer is disabled.
-(Void) viewDidDisappear :( BOOL) animated
{
// Disable the timer
[Self. myTimer setFireDate: [NSDate distantFuture]; // very distant future
}