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];
    }
}

猜你喜欢

转载自blog.csdn.net/rdsuncn1977/article/details/54709256