我的NSTimerselect器不运行。 为什么?
我的代码是:
-(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]; ... }
当我debugging时, createTimer
方法运行正常,但方法timerRun
不运行?
只是创build一个计时器不会开始运行。 您需要同时创build并安排它。
如果你希望它在后台线程上运行,你实际上将不得不做更多的工作。 NSTimer
附加到NSRunloop
,它是事件循环的cocoaforms。 每个NSThread
固有地有一个运行循环,但你必须告诉它明确运行。
一个附带定时器的运行循环可以无限期地运行,但是你可能不希望这样做,因为它不会为你pipe理自动释放池。
所以,总之,你可能想(i)创build计时器; (ii)将其附加到该线程的运行循环; (三)进入一个循环,创build一个自动释放池,运行循环一点,然后消耗自动释放池。
代码可能如下所示:
// 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];
你必须安排一个计时器来运行。 它们被连接到一个运行循环,然后根据需要更新计时器。
您可以将createTimer
更改为
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
或添加
[[NSRunLoop currentRunLoop] addTimer:timer forModes:NSRunLoopCommonModes];
您在scheduledTimerWithTimeInterval中使用的方法签名:target:selector:userInfo:repeats:必须为NSTimer提供参数,因为它将自身作为parameter passing。
你应该改变你的消息签名:
(void)timerRun:(NSTimer *)timer;
这个论据你不需要做任何事情,但是它应该在那里。 同样在createTimer中,select器将变成@selector(timerRun :),因为它现在接受一个参数:
timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerRun:) userInfo:nil repeats:YES];