Enable and disable the NSTimer timer in iOS, iosnstimer

Source: Internet
Author: User

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

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.