【问题标题】:Increase timeInterval of a Timer [duplicate]增加计时器的时间间隔[重复]
【发布时间】:2011-10-09 15:21:53
【问题描述】:
可能重复:
Change the time interval of a Timer
所以我有一个计时器:
timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];
我希望计时器每十秒减少一次,scheduledTimerWithTimeInterval 在十秒后变为 1.5,然后在 10 秒后变为 1.0... 是否可以这样做,如果可以,我该怎么做?
【问题讨论】:
标签:
iphone
timer
nstimeinterval
【解决方案1】:
您无法在创建计时器后对其进行修改。要更改计时器间隔,请使旧计时器无效并使用新间隔创建一个新计时器。
【解决方案2】:
您不必使用多个计时器,您所要做的就是添加一个用于时间间隔的变量,然后创建一个使计时器无效的方法,更改变量并再次启动计时器。例如,您可以创建一个启动计时器的方法。
int iTimerInterval = 2;
-(void) mTimerStart {
timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];
}
-(void) mTimerStop {
[timer invalidate];
iTimerInterval = iTimerInterval + 5;
[self mTimerStart];
}
这将是减少定时器间隔并保持定时器运行的简单方法,但我个人更喜欢使用下面的方法,因为它确保定时器只运行一次,这样它就不会复制实例,迫使您的应用出现故障,这也让您的事情变得更轻松。
int iTimerInterval = 2;
int iTimerIncrementAmount = 5;
int iTimerCount;
int iTimerChange = 10; //Variable to change the timer after the amount of time
bool bTimerRunning = FALSE;
-(void) mTimerToggle:(BOOL)bTimerShouldRun {
if (bTimerShouldRun == TRUE) {
if (bTimerRunning == FALSE) {
timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(mCreateNewImage) userInfo:nil repeats:YES];
bTimerRunning = TRUE;
}
} else if (bTimerShouldRun == FALSE) {
if (bTimerRunning == TRUE) {
[timer invalidate];
bTimerRunning = FALSE;
}
}
}
-(void) mCreateNewImage {
//Your Code Goes Here
if (iTimerCount % iTimerChange == 0) { //10 Second Increments
iTimerInterval = iTimerInterval + iTimerIncrementAmount; //Increments by Variable's amount
[self mTimerToggle:FALSE]; //Stops Timer
[self mTimerToggle:TRUE]; //Starts Timer
}
iTimerCount ++;
}
-(void) mYourMethodThatStartsTimer {
[self mTimerToggle:TRUE];
}
我没有完成所有的编码,但这就是你需要的大部分。只需更改一些内容,您就可以开始了!
【解决方案3】:
您将需要一组或一系列计时器,每个计时器用于不同的时间间隔。当您想更改时间序列中的下一个时间间隔时,停止/使一个计时器无效并启动下一个计时器。