【问题标题】:Threaded NSTimer线程化的 NSTimer
【发布时间】:2010-07-01 09:17:29
【问题描述】:

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

-(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 函数被调用得太频繁了,从而使单个计时器看起来运行得非常快?使用辅助线程启动和重新启动计时器的最佳方法是什么?请注意,这个问题似乎只有在反复快速按下跳过按钮时才会发生,而如果只是偶尔按下它就可以正常工作?

有人有什么想法吗?非常感谢

朱尔斯

【问题讨论】:

    标签: iphone cocoa-touch nstimer nsthread


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的帮助。这可能有效,但我遇到的真正问题是为什么计时器没有失效? Timer 是一个类属性,我在辅助线程上创建它。当涉及到在主线程上完成此操作时,这可能是原因吗?
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 2011-03-21
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多