我的NSTimer的选择器无法运行.为什么? [英] The selector of my NSTimer does not run. Why?

查看:70
本文介绍了我的NSTimer的选择器无法运行.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

-(void) timerRun{...}

-(void) createTimer
{
   NSTimer *timer;
   timer = [NSTimer timerWithTimeInterval:1.0 
                                   target:self 
                                 selector:@selector(timerRun) 
                                 userInfo:nil 
                                  repeats:YES];
}

viewDidLoad
{
   [NSThread detachNewThreadSelector:@selector(createTimmer) 
                            toTarget:self withObject:nil];
   ...

}

当我调试时,方法createTimer运行正常,但是方法timerRun没有运行?

When I debug, the method createTimer runs ok, but the method does timerRun not run?

推荐答案

仅创建计时器并不会启动计时器.您需要创建它并计划它.

Just creating a timer doesn't start it running. You need to both create it and schedule it.

如果要在后台线程上运行,实际上您要做的工作要比实际要做的多. NSTimer附加到NSRunloop,这是事件循环的可可形式.每个NSThread本质上都有一个运行循环,但是您必须告诉它明确运行.

You're actually going to have to do slightly more work than that if you want it to run on a background thread. NSTimers attach to NSRunloops, which are the Cocoa form of an event loop. Each NSThread inherently has a a run loop but you have to tell it to run explicitly.

带有计时器的运行循环可以无限期地运行,但是您可能不希望这样做,因为它将不会为您管理自动释放池.

A run loop with a timer attached can run itself indefinitely but you probably don't want it to because it won't be managing autorelease pools for you.

因此,总而言之,您可能想要(i)创建计时器; (ii)将其附加到该线程的运行循环中; (iii)进入一个创建自动释放池的循环,运行一下运行循环,然后耗尽自动释放池.

So, in summary, you probably want to (i) create the timer; (ii) attach it to that thread's run loop; (iii) enter a loop that creates an autorelease pool, runs the run loop for a bit and then drains the autorelease pool.

代码可能类似于:

// create timer
timer = [NSTimer timerWithTimeInterval:1.0 
                                target:self 
                              selector:@selector(timerRun) 
                              userInfo:nil 
                               repeats:YES];

// attach the timer to this thread's run loop
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

// pump the run loop until someone tells us to stop
while(!someQuitCondition)
{
    // create a autorelease pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // allow the run loop to run for, arbitrarily, 2 seconds
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];

    // drain the pool
    [pool drain];
}

// clean up after the timer
[timer invalidate];

这篇关于我的NSTimer的选择器无法运行.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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