NSTimer和更新UI [英] NSTimer and updating UI

查看:177
本文介绍了NSTimer和更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力让我的游戏在 NSTimer 下正常工作。我看到很多人对我有一个类似的问题,我只需要一些澄清的东西。

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.

基本上我有一个 NSTimer 在主线程上运行,它正在更新代表时间的图像,有一个mapView。当用户平移地图时,定时器被阻塞。我的问题是,如果我创建一个新的线程并添加定时器到其runloop,当我执行选择器(更新UI)将不会阻塞定时器线程?我也知道这是坏习惯,从次要线程更新UI,我该怎么办?

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:阻塞了定时器,因为它们都在同一个运行循环中运行。我现在已经解决了这个与定时器线程与其自己的运行循环,但这导致我的第二个问题,我非常卡住!这里是代码...

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];
}

这段代码给我一个[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?

推荐答案

如果你为你的计时器创建一个线程,你仍然需要在主线程上做UI更新。您可以使用 performSelectorOnMainThread:withObject:waitUntilDone: NO 这将排队主线程上的方法调用而不阻塞计时器线程。

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.

但是,如果主线程的 runloop 被地图平移所阻挡(为什么?)UI更新仍会在事件中等待队列,直到地图平移完成。

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.

这篇关于NSTimer和更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆