Skip to content

Instantly share code, notes, and snippets.

@CodaFi
Last active December 17, 2015 16:38
Show Gist options
  • Save CodaFi/5639819 to your computer and use it in GitHub Desktop.
Save CodaFi/5639819 to your computer and use it in GitHub Desktop.
Check for multiple instances of a Cocoa Application. it is recommended that this be checked for in `applicationWillFinishLaunching:`.
static NSMachPort *existancePort = nil;
/**
* Used by the CFICheckForOtherRunningInstancesOfCurrentApplication() function to
* create a unique NSMachPort object. This string *CANNOT CHANGE* in the future,
* otherwise conflicting versions of an App will run on the same machine and
* defeat the purpose of this function.
*/
static NSString *const CFIPortNameConstant = @"SomeNon-ArbitraryPortName";
/**
* Attempts to find out whether the same port has been registered twice with
* the Mach Bootstrap server. If so, a message is presented and the other
* instance of the app will terminate.
*/
static void CFICheckForOtherRunningInstancesOfCurrentApplication() {
if (existancePort == nil) {
existancePort = [[NSMachPort alloc] init];
}
BOOL noOtherInstance = [[NSMachBootstrapServer sharedInstance]registerPort:existancePort name:CFIPortNameConstant];
if (noOtherInstance) return;
NSString *applicationName = NSBundle.mainBundle.infoDictionary[@"CFBundleName"];
NSString *alertText = [NSString stringWithFormat:@"Another instance of %@ is already running!", applicationName];
NSString *alertInformativeText = [NSString stringWithFormat:@"Please quit the other instance of %@", applicationName];
//The `%@, String` redundancy courtesy the Apple engineer who thought that was a good idea at the time.
NSAlert *instanceAlert = [NSAlert alertWithMessageText:alertText defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", alertInformativeText];
[instanceAlert runModal];
[existancePort invalidate];
[NSRunningApplication.currentApplication terminate];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment