Change the time interval of a Timer

故事扮演 提交于 2020-01-21 23:44:46

问题


here is my question: Is it possible to increase the scheduledTimerWithTimeInterval:2 for example of "3" after 10 seconds in ViewDidLoad for example. E.g., from this:

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];

to this:

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];

thank you sorry for my english I french :/


回答1:


Reschedule the timer recursively like this:

float gap = 0.50;

[NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO];

-(void) onTimer {
    gap = gap + .05;
    [NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO];
}

========

Or according to How can I update my NSTimer as I change the value of the time interval

Invalidate it with:

[myTimer invalidate];

Then create a new one with the new time. You may have to set it to nil first as well.

myTimer = nil;
myTimer = [NSTimer scheduledTimerWithTimeInterval:mySlider.value 
                                           target:self 
                                         selector:@selector(myMethod) 
                                         userInfo:nil 
                                          repeats:YES];



回答2:


Use setFireDate: to reschedule the timer. You'll need to keep track of the timer in an ivar. For example:

@property (nonatomic, readwrite, retain) NSTimer *timer;

@synthesize timer=timer_;

- (void)setTimer:(NSTimer *)aTimer {
  if (timer_ != aTimer) {
    [aTimer retain];
    [timer_ invalidate];
    [timer_ release];
    timer_ = aTimer;
  }

- (void)dealloc {
  [timer_ invalidate];
  [timer_ release];
}

...

self.timer = [NSTimer scheduledTimerWithTimeInterval:...];

...

self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3]; // reschedule for 3 seconds from now


来源:https://stackoverflow.com/questions/7518180/change-the-time-interval-of-a-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!