Ive been trying to get my game to work correctly with an NSTimer
. Ive seen many people have had a similar problem to me and I just need a bit of clarification on something.
Basically I have an NSTimer
running on the main thread which is updating images which represent the time, but I also have a mapView. When the user pans the map the timer is blocked. My question is if I create a new thread and add the timer to its runloop, when I perform selector (which updates UI) will this not block the timer thread again? Also I know it is bad practise to update the UI from secondary thread so how would I go about that?
UPDATE: I think the mapView was blocking the timer as they were both running in the same run loop. I have now fixed this with a timer thread with its own run loop, however this has led me to a 2nd problem which has me extremely stuck!! Here is the code...
//called when I need to restart the timer
[NSThread detachNewThreadSelector:@selector(resumeTimer) toTarget:self withObject:nil];
-(void) restartTimer {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
timer=[NSTimerscheduledTimerWithTimeInterval:1.
target:self
selector:@selector(dim)
userInfo:nil
repeats:YES];
[self performSelectorOnMainThread:@selector(timerImageUpdate)
withObject:nil
waitUntilDone:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
[pool drain];
}
This code gives me a Bad_access error on the [pool drain];
I have run the code in instruments and still cannot see why it gives me the error. Any ideas?
If you create a thread for your timer, you still have to do the UI update on the main thread. You can do that with performSelectorOnMainThread:withObject:waitUntilDone:NO which will queue the method call on the main thread without blocking the timer thread.
However, if the main thread's runloop is blocked by the map panning (why?) the UI update will still be waiting in the event queue for the until the map pan is done.