Ios 我的NSTimer的选择器未运行。为什么?
我的代码是:Ios 我的NSTimer的选择器未运行。为什么?,ios,nstimer,Ios,Nstimer,我的代码是: -(void) timerRun{...} -(void) createTimer { NSTimer *timer; timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerRun)
-(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
吗 在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];
你必须安排一个计时器让它运行。它们连接到一个运行循环,该循环会根据需要更新计时器 您可以将
createTimer
更改为
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerRun)
userInfo:nil
repeats:YES];
或添加
[[NSRunLoop currentRunLoop] addTimer:timer forModes:NSRunLoopCommonModes];
仅仅创建一个计时器并不能启动它的运行。您需要创建它并安排它 如果你想让它在后台线程上运行,你实际上需要做的工作要稍微多一些
NSTimer
s附加到nsrunlop
s,这是事件循环的一种形式。每个NSThread
本身都有一个运行循环,但您必须告诉它显式运行
带有计时器的运行循环可以无限期地自行运行,但您可能不希望它这样做,因为它不会为您管理自动释放池
总之,您可能希望(i)创建计时器;(ii)将其连接至该螺纹的运行回路;(iii)输入创建自动释放池的循环,运行运行循环一段时间,然后排空自动释放池
代码可能如下所示:
// 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];
@selector(createTimmer)
可能只是一个输入错误?只是好奇为什么要使用另一个线程来创建计时器。。。出于某种原因,它可能会是一个长时间运行的操作吗?我做了更改,但当我移动代码“[NSTimer scheduledTimerWithTimeInterval:1.0目标:自选择器:@selector(timerRun))时,方法timerRun仍然没有运行userInfo:nil重复:YES];“在viewDidLoad中,timerRun运行正常。我认为问题在于Differents线程。但是我不想让计时器在Main线程中运行。看看Tommy的回答,他更详细了,解决了你的问题。谢谢,我发现了我的错误。我添加您的代码:“while(!someQuitCondition){//创建自动释放池NSAutoreleasePool*池=[[NSAutoreleasePool alloc]init];//允许运行循环任意运行2秒[[nsrunlop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//排空池[pool drain];”,然后计时器运行正常。