1. 程式人生 > >Cocoa 禁止APP多重啟動

Cocoa 禁止APP多重啟動

啟動時阻止多開

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self.window setIsVisible:NO];
    [AppDelegate deduplicateRunningInstances];
    [self.window setIsVisible:YES];
}

具體實現

+ (void)deduplicateRunningInstances {
    if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[[NSBundle
mainBundle] bundleIdentifier]] count] > 1) { // deprecated // [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]] // defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]]]; [alert setInformativeText:@"This copy will now quit."]; [alert runModal]; [NSApp terminate:nil
]; } }