2011-11-18 61 views
3

我的代码是:我的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运行的方法?

+0

'@selector(createTimmer)'大概只是一个错字? – Tommy

+0

只是好奇你为什么使用另一个线程来创建定时器...是否由于某种原因,预计会长时间运行? – devios1

回答

12

只需创建一个定时器不启动它运行。您需要同时创建它并安排它。

如果您希望它在后台线程上运行,您实际上将不得不做更多的工作。 NSTimer附加到NSRunloop s,这是事件循环的可可形式。每个NSThread固有地有一个运行循环,但你必须告诉它明确运行。

带有定时器的运行循环可以无限期运行,但您可能不希望它,因为它不会为您管理自动释放池。

因此,总之,你可能想(i)创建计时器; (ii)将其附加到该线程的运行循环中; (三)进入一个循环,创建一个自动释放池,运行循环一点,然后消耗自动释放池。

代码可能会是这样的:

// 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]; 
+0

谢谢,我发现我的错误。我添加你的代码:“while(!someQuitCondition) { //创建一个自动释放池 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //允许运行循环运行,任意2秒 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]]; //排水池 [pool drain]; }“,然后timerRun运行正常。 – user797876

2

您在scheduledTimerWithTimeInterval中使用的方法签名:target:selector:userInfo:repeats:必须为NSTimer提供参数,因为它将自身作为参数传递。

您应该将消息签名改为:

(void)timerRun:(NSTimer *)timer; 

你不需要用参数做任何事情,但它应该在那里。此外,在createTimer选择将成为@selector(timerRun :)因为它现在接受一个参数:

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

你必须安排一个计时器,它运行。它们被连接到一个运行循环,然后根据需要更新计时器。

您可以更改createTimer

[NSTimer scheduledTimerWithTimeInterval:1.0 
            target:self 
           selector:@selector(timerRun) 
           userInfo:nil 
            repeats:YES]; 

或添加

[[NSRunLoop currentRunLoop] addTimer:timer forModes:NSRunLoopCommonModes]; 
+0

我有变化,但方法timerRun仍然没有运行过程中出现,当我移动码 “[的NSTimer scheduledTimerWithTimeInterval:1.0 目标:自 选择器:@selector(timerRun) USERINFO:无 重复:YES];”在viewDidLoad中,timerRun运行正常。我认为问题在于不同的线程,但我想让计时器不在mainthread中运行 – user797876

+0

看看Tommy的答案,他更加详细并解决了您的问题。 –

相关问题