2011-03-29 38 views
0

我有一個使用Dave DeLong的DDHotKey類編寫的演示應用程序(一個精彩的編碼,順便說一句),我想知道我應該從哪裏看該類將在應用程序開始後立即啓動?在應用程序啓動時執行一個類Objective-C

具體而言,我想在程序執行時運行類中的兩個函數,即registerhotkey(由Dave DeLong提供的示例代碼中的registerexample1)和unregisterhotkey(由Dave DeLong提供的示例代碼中的unregisterexample1)節目分別關閉。

我不確定如何做到這一點,我正在尋找一個指導,看看我應該看什麼或只是一些基本的指針。

謝謝!

回答

4

最簡單的方法是在應用程序委託中的applicationDidFinishLaunching:方法中。這在啓動時被調用。當應用程序即將退出時,將調用applicationWillTerminate:方法。

// in application delegate 
- (void)applicationDidFinishLaunching:(NSNotification *)notification { 
    // call registerhotkey 
} 
- (void)applicationWillTerminate:(NSNotification *)notification { 
    // call unregisterhotkey 
} 

或者,你可以把你的主函數的調用,調用registerhotkey調用NSApplicationMain面前,unregisterhotkey調用NSApplicationMain後。如果還沒有,你需要在這個代碼中添加一個自動釋放池。

int main(int argc, char **argv) { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    // call registerhotkey 
    int result = NSApplicationMain(argc,argv); 
    // call unregisterhotkey 
    return result; 
} 

最後,你可以使用特殊的方法load時,裝載的類或類別調用registerhotkey。您實際上不需要撥打unregisterhotkey,因爲系統會在您的應用程序退出時自動執行此操作。

// in any class or category 
+ (void)load { 
    // call registerhotkey 
} 
+0

使用應用程序的委託方法+1是最合適的方法。 'NSApplicationMain()'永遠不會返回,所以之後的任何東西都不會執行。過載'+負載'也被認爲是有風險的。 – 2011-03-29 22:43:04

相關問題