Problems launching an NSTimer from a secondary thread
I'm noticing in my code that when I try to start an NSTimer from a secondary thread, it doesn't work. I tried calling +[NSRunLoop currentRunLoop] just in case the problem was that the thread didn't have a run loop...but no dice. (Note that that was a shot in the dark. The docs said that would create a run loop, but perhaps there's other configuration that I needed to do, and didn't.)
I'm aware of calls like -[NSObject performSelectorOnMainThread:] which could solve my problem (in 开发者_开发问答fact, my solution was to simply move this code into the primary thread, which works fine), but I'm still curious about why this problem occurred. Is it in fact impossible to start an NSTimer from a secondary thread? Is there a workaround?
Thanks very much.
The following code segment works for me.
-(id)init {
myWorkerThread = [[NSThread alloc]initWithTarget:self selector:@selector(workerThread) object:nil];
[myWorkerThread start];
}
#pragma mark WorkerThread Support
-(void)stillWorking {
NSLog(@"Still working...");
}
-(void)workerThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSTimer *threadTimer = [NSTimer scheduledTimerWithTimeInterval:10
target:self
selector:@selector(stillWorking)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:threadTimer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
[pool drain];
}
I found this page with some source code for starting an NSTimer on a secondary thread. Do you actually start the runloop in your code? It's tough to say without seeing your code what the problem may be: http://www.iphonedevsdk.com/forum/iphone-sdk-development/22175-nstimer-secondary-thread-will-produce-leaks.html
John Franklin answer is correct..but when you call the method
scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:
it automatically schedules the timer on the current NSRunLoop. Therefore you don't need to add again the timer to the current run loop, you can only call a [[NSRunLoop currentRunLoop] run]
method.
Make sure you A) add the timer to the current runloop, and B) run said runloop. When your timer fires, if you'd like to exit the [runloop run] invocation, call [runloop stop].
精彩评论