Enable and disable Timer Nstimer in iOS

Source: Internet
Author: User

Call the Timer method once:

?
1 2 myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];  //不重复,只调用一次。timer运行一次就会自动停止运行

To invoke the Timer method repeatedly:

?
1 2 timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];  //每1秒运行一次function方法。  <span style="line-height: 1.5;">  </span>

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 released, so the counter timer must be stopped at viewwillappear time, otherwise the memory leak may result.

Stop the timer from running, but this is the permanent stop:

?
1 2 //取消定时器  [timer invalidate];

To achieve this: stop first, and then in some cases turn on the timer again, you can use the following method:

First off the timer cannot use the method above, should use the following method:

?
1 2 //关闭定时器  [myTimer setFireDate:[NSDatedistantFuture]];

Then you can use the following method to open this timer again:

?
1 2 //开启定时器  [myTimer setFireDate:[NSDatedistantPast]];

Example: For example, when the page disappears, turn off the timer, and then when the page opens again, turn on the timer.

(primarily to prevent it from running in the background, take up the CPU) can be implemented using the following code:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 //页面将要进入前台,开启定时器  -(void)viewWillAppear:(BOOL)animated      //开启定时器      [scrollView.myTimer setFireDate:[NSDate distantPast]];    //页面消失,进入后台不显示该页面,关闭定时器  -(void)viewDidDisappear:(BOOL)animated      //关闭定时器      [scrollView.myTimer setFireDate:[NSDate distantFuture]]; 

OK, get it done.

Official interface

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @interface NSTimer : NSObject //初始化,最好用scheduled方式初始化,不然需要手动addTimer:forMode: 将timer添加到一个runloop中。 + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo; + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;- (void)fire;  //立即触发定时器- (NSDate *)fireDate;//开始时间 - (void)setFireDate:(NSDate *)date;//设置fireData,其实暂停、开始会用到- (NSTimeInterval)timeInterval;//延迟时间- (void)invalidate;//停止并删除 - (BOOL)isValid;//判断是否valid- (id)userInfo;//通常用nil@end

Pause and resume

?
1 2 3 [timer setFireDate:[NSDate date]]; //继续。 [timer setFireDate:[NSDate distantPast]];//开启 [timer setFireDate:[NSDatedistantFuture]];//暂停

  

An example of using Nstimer to implement a countdown:

-(void) viewdidload Add the following code, starting once per second

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES]; - (void)timerFireMethod:(NSTimer*)theTimer {     NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象     NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...奥运时间好了     [endTime setYear:2008];     [endTime setMonth:8];     [endTime setDay:8];     [endTime setHour:8];     [endTime setMinute:8];     [endTime setSecond:8];         NSDate *todate = [cal dateFromComponents:endTime]; //把目标时间装载入date     [endTime release];    NSDate *today = [NSDate date];    //得到当前时间    //用来得到具体的时差     unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;     NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];          NSLog(@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]); }

  

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.