更改计时器的时间间隔

时间:2011-09-22 16:24:50

标签: iphone xcode timer nstimer nstimeinterval

这是我的问题: 例如,在ViewDidLoad中10秒后是否可以增加scheduledTimerWithTimeInterval:2例如“3”。 例如,来自:

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

到此:

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];
谢谢你 对不起我的英语我法语:/

2 个答案:

答案 0 :(得分:1)

递归重新安排计时器,如下所示:

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];
}

======

或根据How can I update my NSTimer as I change the value of the time interval

使用以下内容使其失效:

[myTimer invalidate];

然后用新时间创建一个新的。您可能还必须先将其设置为nil。

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

答案 1 :(得分:0)

使用setFireDate:重新安排计时器。你需要在ivar中跟踪计时器。例如:

@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