gpt4 book ai didi

iphone - 如何在 objective-c 中取消调度 NSTimer

转载 作者:太空狗 更新时间:2023-10-30 03:46:17 25 4
gpt4 key购买 nike

我在应用程序中使用嵌套的 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)];
}

最佳答案

  • 使用[tmLevel invalidate]取消定时器的调度。
  • 不要忘记在之后立即设置tmLevel=nil(以避免在定时器被 Runloop 取消调度和释放后使用该变量)
  • 不要忘记在失去对它的引用之前使 tmLevel 计时器无效,即在将新的 NSTimer 分配给 tmLevel 变量之前调用 [tmLevel invalidate](否则之前的计时器将继续在新的之外运行)

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

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

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

你的第一行完全没用,有点像你在做

int x = 5;
x = 12; // of course the value "5" is lost, replaced by the new value

关于iphone - 如何在 objective-c 中取消调度 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7334552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com