2013-05-27 33 views
2

我希望能夠設置一個計時器來計數23秒,然後執行一個功能。我怎麼能這樣做?我需要NSTimer嗎?如何安排延遲後運行的方法

+0

你閱讀的NSTimer的文檔,並用它嘗試? – Wain

+1

您可以使用'[self performSelector:withObject:afterDelay:]' – Larme

+0

這些天,現代編譯器和塊,我只是使用'dispatch_after'。無需編寫單獨的回調函數。 – Abizern

回答

2

只需使用

[NSTimer scheduledTimerWithTimeInterval:23.0 target:self selector:@selector(myThingToDo) options:nil]; 

打在移動,測試第一。

此外,還有一個neat category可用,允許您使用NSTimer與塊!

+0

我最近偶然發現'NSTimer'上一個整潔的類別,使用'NSTimer'和塊(https://github.com/jivadevoe/NSTimer-Blocks)結合使用。 –

+0

@Bart謝謝!那很整齊。 – Undo

+0

或https://github.com/Abizern/NSTimer-JCSBlocks,它也可以讓你安排一個可重複的計時器,或一個可中斷的計時器。 – Abizern

1

你可以直接使用GCD的方法,既節約了無需編寫單獨的回調函數:

// Just for clarity I'm defining the time period separately, 23 seconds from now. 
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 23 * NSEC_PER_SEC); 

dispatch_after(delay, dispatch_get_main_queue(), ^{ 
    // Anything in here will be run on the main queue 23 seconds from now. 
});