Threaded NSTimer

这一生的挚爱 提交于 2019-12-31 04:25:06

问题


I am aware of the many questions regarding this topic, as I myself have asked one previously however, my issue now seems to be more related to the threading part. I have the following 2 methods.

-(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];

}

The restartTimer function is called when the game begins. This works fine and the timer fires the dim selector nicely. The problem occurs when the user clicks my skip button in quick succession. [skip] updates an MKMapView and in the delegate method mapdidfinishloading the follwing is called : [NSThread detachNewThreadSelector:@selector(restartTimer) toTarget:self withObject:nil];
When this happens it seems several timers are created and thus my dim function is called far too often giving the appearance of the single timer running really fast? What is the best way to start and restart the timer using a secondary thread? Note this problem only seems to happen if the skip button is pressed repeatedly and quickly, while it works fine if just pressed now and again?

Anyone have any ideas? Many thanks

Jules


回答1:


You can use a bool to know if you have a timer running or not. When you start the timer you set it to true, when you stop the timer you set it to false. When resume timer function is called you check this variable and if it's true you do not start a new timer.

Another solution would be to limit user interaction with the button. If the button is pressed you make it inactive for a time.



来源:https://stackoverflow.com/questions/3156452/threaded-nstimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!