2010-02-07 134 views
6

我一直在成功使用NSTimer,但现在遇到了麻烦。毫无疑问有些愚蠢。欣赏另一组眼睛。运行调试器,我看到applicationDidFinishLaunching被调用,但是从不调用触发器。NStimer - 我在这里做错了什么?

-(void) trigger:(NSTimer *) theTimer{ 
    NSLog(@"timer fired"); 
} 

- (void)applicationDidFinishLaunching:(UIApplication *)application {  

    nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(trigger) userInfo:nil repeats:YES]; 

    [window makeKeyAndVisible]; 
} 
+0

以及以下所述,如果不使用垃圾回收,您必须保留计时器。 – 2010-02-07 22:11:52

+2

如果您添加计时器来运行循环,则不需要保留它,我认为运行循环会保留它。 – Jaanus 2010-02-07 22:48:35

+0

谢谢大家捕捉方法签名错误。另一件让我恼火的事情是我使用了scheduledTimerWithInterval,它不需要手动添加到运行循环中。在这种情况下,我忘记了scheduledTimer部分。 – morgancodes 2010-02-07 23:31:17

回答

13

选择器必须具有以下特征:

- (void)timerFireMethod:(NSTimer*)theTimer 

,所以你需要

@selector(trigger:) 

- 编辑 -

也许你正在做别的地方本,但在代码你包括你实际上并没有启动计时器。您必须将其添加到NSRunLoop才能触发任何事件。

[[NSRunLoop currentRunLoop] addTimer:nst forMode:NSDefaultRunLoopMode]; 

如果我正确地阅读了这些示例。我只使用init方法自动将它添加到当前的NSRunLoop中。你真的应该看看有人在我的文章的评论中包含的开发人员文档。

+1

呃再次太慢了,对不起诺亚:) – willcodejavaforfood 2010-02-07 22:03:45

+0

+1这里是相关的文档:http://developer.apple.com/mac/library/documentation/cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html #// apple_ref/occ/clm/NSTimer/timerWithTimeInterval:target:selector:userInfo:repeatats: – 2010-02-07 22:04:09

+1

澄清: - :是方法名称的一部分。 Infact:是一个有一个参数的方法的完全有效的方法名称。 – 2010-02-07 22:10:11

1

你给定时器,trigger的选择,表明它应该调用不带参数的方法。要么改变你的计时器烧法

- (void)trigger 
{ 
     // look at me, I don't take any parameters 
     NSLog(@"timer fired"); 
} 

或更改初始计时器调用使用@selector(trigger:)

+1

定时器回调必须有一个参数,所以改变方法名称为“触发”不会工作 – 2010-02-07 22:11:07

+2

@jib - 不,这是不正确的。没有NSTimer参数,定时器回调工作正常。我一直这么做。 – 2010-02-07 23:12:58

2

两件事情:

1)有人说,该方法应具有以下特征..

-(void) trigger:(NSTimer *) theTimer; 

和你做这样的计时器:

nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(trigger:) userInfo:nil repeats:YES]; 

2)只创建定时器不会运行它。作为the documentation says

您必须将新的计时器添加到运行 循环,使用addTimer:forMode :.然后, 经过几秒钟后,触发定时器 ,调用调用。 (如果 定时器配置重复,有 无需随后 计时器重新添加到运行循环。)

这里是一块真正的功能代码,您可以模拟后。定时器的创建与你的定时器相同,但它也以正确的方式将其添加到runloop。

[[NSRunLoop currentRunLoop] addTimer: 
    [NSTimer timerWithTimeInterval:0.1 
          target:self 
          selector:@selector(someSelector:) 
          userInfo:nil 
          repeats:NO] 
           forMode:NSDefaultRunLoopMode]; 
+4

+1这是正确的。你也可以使用'scheduledTimer ...'方便的方法,将定时器添加到你的运行循环中。 – 2010-02-07 22:40:39

0

你的问题是由于timerWithTimeInterval:target:selector:userInfo:repeats:创建一个计时器,但确实不时间表它的运行循环,你必须自己做的事实。

不过,你不妨使用此方法,创建计时器安排它的运行循环:在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {不是在主线程启动计时器时,我有一个问题,scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

0

dispatch_async(dispatch_get_main_queue(), ^{ 
[self startScheduledTimer]; 
}); 
相关问题