views:

61

answers:

1

Hi all, 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

A: 

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.

Felics
Thanks for your help. This may work but the real issue Im having is why the timer is not invalidating? Timer is a class property and I create it on a secondary thread. When it comes to invalidating this is done on the main thread, could this be the cause?
Jules