1

我知道关于这个主题的许多问题,正如我自己之前问过的那样,但是我现在的问题似乎与线程部分更相关。我有以下两种方法。

-(void) restartTimer {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1. 
                                             target:self
                                           selector:@selector(dim) 
                                           userInfo:nil 
                                            repeats:YES];
    time = 31;
    NSLog(@"calling restart timer");
    [self performSelectorOnMainThread:@selector(timerImageUpdate) withObject:nil waitUntilDone:NO];

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

    [pool drain];

}

-(void) resumeTimer {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1. 
                                             target:self
                                           selector:@selector(dim) 
                                           userInfo:nil 
                                            repeats:YES];
    NSLog(@"calling resume timer");

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

    [pool drain];

}

游戏开始时调用 restartTimer 函数。这工作正常,计时器很好地触发了暗淡选择器。当用户快速连续单击我的跳过按钮时,就会出现问题。[skip] 更新 MKMapView 并在委托方法 mapdidfinishloading 中调用以下方法: [NSThread detachNewThreadSelector:@selector(restartTimer) toTarget:self withObject:nil];
发生这种情况时,似乎创建了多个计时器,因此我的 dim 函数被调用得太频繁了,从而使单个计时器看起来运行得非常快?使用辅助线程启动和重新启动计时器的最佳方法是什么?请注意,这个问题似乎只有在反复快速按下跳过按钮时才会发生,而如果只是不时按下它就可以正常工作?

有人有想法么?非常感谢

朱尔斯

4

1 回答 1

0

您可以使用 bool 来了解您是否正在运行计时器。当您启动计时器时将其设置为 true,当您停止计时器时将其设置为 false。当调用恢复计时器功能时,您检查此变量,如果为真,则不启动新计时器。

另一种解决方案是限制用户与按钮的交互。如果按下按钮,您将使其在一段时间内处于非活动状态。

于 2010-07-01T09:31:06.460 回答