我一直在努力让我的游戏能够正常运行NSTimer
。我发现很多人都遇到了与我类似的问题,我只需要对某些事情进行一些澄清。
基本上我有一个NSTimer
在主线程上运行,该线程正在更新代表时间的图像,但我也有一个地图视图。当用户平移地图时,计时器被阻止。我的问题是,如果我创建一个新线程并将计时器添加到其运行循环中,当我执行选择器(更新 UI)时,这不会再次阻塞计时器线程吗?我也知道从辅助线程更新 UI 是不好的做法,那么我该如何处理呢?
UPDATE:我认为 mapView 阻塞了计时器,因为它们都在同一个运行循环中运行。我现在已经用一个带有自己的运行循环的计时器线程修复了这个问题,但这导致了我遇到了第二个问题,这让我陷入了困境!这是代码...
//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];
}
这段代码给了我一个[池排水]上发生 Bad_access 错误;
我已经在仪器中运行了代码,但仍然不明白为什么它会给我这个错误。有任何想法吗?
如果您为计时器创建一个线程,您仍然需要在主线程上进行 UI 更新。你可以这样做PerformSelectorOnMainThread:withObject:waitUntilDone: http://developer.apple.com/iphone/library/documentation/cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:NO它将在主线程上对方法调用进行排队,而不会阻塞计时器线程。
但是,如果主线程的runloop http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1被地图平移阻止(为什么?)UI 更新仍将在事件队列中等待,直到地图平移完成。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)