如何在objective-c中取消计划NSTimer

Shi*_*edi 5 iphone static timer objective-c

我在应用程序中使用嵌套的NSTimer.我这里有两个问题.

  1. 如何在此功能中重新启动时间计数器 - (void)updateLeftTime:(NSTimer *)theTimer
  2. 如何杀死前一个计时器因为- (void)updateLevel:(NSTimer *)theTimer也是由计时器调用.

- (void)viewDidLoad {
    [super viewDidLoad];

    tmLevel=[NSTimer scheduledTimerWithTimeInterval:20.0f target:self selector:@selector(updateLevel:) userInfo:nil repeats:YES];

    tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLeftTime:) userInfo:nil repeats:YES];
}

- (void)updateLevel:(NSTimer *)theTimer {
    static int count = 1;
    count += 1;

    lblLevel.text = [NSString stringWithFormat:@"%d", count];

    tfLeftTime.text=[NSString stringWithFormat:@"%d",ANSWER_TIME];

    tmLeftTime=[[NSTimer alloc] init];
    tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLeftTime:) userInfo:nil repeats:YES];
    [self playMusic];

}
- (void)updateLeftTime:(NSTimer *)theTimer {
    static int timeCounter=1;
    timeCounter+=1;
    tfLeftTime.text=[NSString stringWithFormat:@"%d", (ANSWER_TIME-timeCounter)];
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*are 17

  • 使用[tmLevel invalidate]取消计时器的时间表.
  • 不要忘记在tmLevel=nil紧接着之后设置(以避免在计划程序未被计划并由Runloop释放后使用变量)
  • 在丢失对它的引用之前不要忘记使tmLevel定时器无效,即[tmLevel invalidate]在将新的NSTimer分配给tmLevel变量之前调用(否则先前的定时器将继续运行除新的定时器之外)

另请注意,在您的代码中,您有无用的分配,而且还会创建泄漏:

tmLeftTime=[[NSTimer alloc] init];
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLeftTime:) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

在这里你分配一个NSTimer实例,将这个实例存储在tmLeftTime...然后立即忘记这个创建的实例,用另一个替换它,使用[NSTimer scheduledTimerWithTimeInterval:...]!因此,使用的NSTimer [[NSTimer alloc] init]丢失了,并且正在创建泄漏(因为它永远不会被释放).

你的第一行完全没用,就像你在做的那样

int x = 5;
x = 12; // of course the value "5" is lost, replaced by the new value
Run Code Online (Sandbox Code Playgroud)


che*_*ewy 11

当您想要重置计时器时,请添加以下行

[tmLeftTime invalidate]; 
tmLeftTime = nil;
Run Code Online (Sandbox Code Playgroud)

你也可以用

if ([tmLeftTime isValid]){
  // the timer is valid and running, how about invalidating it
  [tmLeftTime invalidate]; 
    tmLeftTime = nil;
}
Run Code Online (Sandbox Code Playgroud)