2

我一直在尝试让我的游戏与NSTimer. 我见过很多人和我有类似的问题,我只是需要澄清一些事情。

基本上我NSTimer在主线程上运行,它正在更新代表时间的图像,但我也有一个 mapView。当用户平移地图时,计时器被阻止。我的问题是,如果我创建一个新线程并将计时器添加到其运行循环中,当我执行选择器(更新 UI)时,这不会再次阻塞计时器线程吗?另外我知道从辅助线程更新 UI 是不好的做法,那么我该怎么做呢?

更新:我认为 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];
}

这段代码在 [pool drain] 上给了我一个 Bad_access 错误

我已经在仪器中运行了代码,但仍然看不到它为什么会给我错误。有任何想法吗?

4

1 回答 1

2

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.

于 2010-06-28T12:46:49.487 回答