Use/turn-on and off of timer Nstimer in iOS

Source: Internet
Author: User

One. Only one timer method is called:

Do not repeat, call only once. Timer runs once and stops automatically

MyTimer = [Nstimer scheduledtimerwithtimeinterval:1.5 target:self selector: @selector (function:) Userinfo:nil repeats: NO];

Two. Repeat the call timer method:

Run the function method once every 2 seconds.

Timer = [Nstimer scheduledtimerwithtimeinterval:2.0 target:self selector: @selector (function:) Userinfo:nil repeats: YES];

Note: When you set the counter's repeats to Yes, the reference count of self is incremented by 1. As a result, self (that is, Viewcontroller) cannot be freed, so you must stop the counter timer in the Viewdiddisappear method, or it may cause a memory leak.

Three. Stop the timer completely: (This is the timer permanent stop, after the stop, be sure to empty the timer, otherwise it is not released, will cause unnecessary memory overhead)

  Cancel Timer

[Timer invalidate];

Timer = nil;

Four. Turn off the timer when the page disappears, and then turn on the timer when the page opens again

  The page will enter the foreground, turn on the timer

-(void) Viewwillappear: (BOOL) animated

{

//Turn on timer

[Self.mytimer setfiredate:[nsdate Distantpast]; It's a long way past.

}

  The page disappears, goes into the background does not display this page, closes the timer

-(void) Viewdiddisappear: (BOOL) animated

{

//Off timer

[Self.mytimer setfiredate:[nsdate distantfuture]; A far future.

}

Use/turn-on and off of timer Nstimer in iOS

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.