Execute a class at application start in Objective-C

1.2k views Asked by At

I have a demo application written in Objective-C that makes use of Dave DeLong's DDHotKey class (a brilliant piece of coding, btw) and I was wondering where should I look at getting the class to launch as soon as the application begins?

Specifically, there are two functions in the class, registerhotkey (registerexample1 in the example code provided by Dave DeLong) and unregisterhotkey (unregisterexample1 in the example code provided by Dave DeLong) that I would like to run at program execution and at program close respectively.

I'm not really sure how to do this and am looking either for a guide as to where I should look or just some basic pointers.

Thanks!

1

There are 1 answers

1
ughoavgfhw On BEST ANSWER

The easiest way to do it is in the applicationDidFinishLaunching: method in your app delegate. This is called on startup. The applicationWillTerminate: method will be called when the application is about to exit.

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

Alternatively, you could place the calls in your main function, calling registerhotkey before the call to NSApplicationMain, and unregisterhotkey after the call to NSApplicationMain. If there isn't one already, you will need to add an autorelease pool around this code.

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

Finally, you could use the special load method to call registerhotkey when a class or category is loaded. You actually don't need to call unregisterhotkey because the system will do it automatically when your application quits.

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