2010-02-07 129 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]; 
}); 
相關問題