Replacing Cocoa applications with a new instance

Sometimes you need to start a Cocoa application and have it replace a previously running instance of itself. In the case of the application that we are writing it is invoked by the open command line command and we then want it to replace a previously running version of the program. If the application is activated from the GUI we want the default behaviour going to the open application to be preserved.
The solution is in 2 parts:
  • Use the -n option to open to invoke a new instance of the Cocoa application
  • Have the application kill any other instances of itself

Opening a new instance of an Application


open -n /Application/myApp

Code to close earlier instances of Application


In the application delegate insert code to locate all applications with the same bundle identifier and who are not us and ask them to terminate.


-(id) init
{
self = [super init];

if (self)
{
// if there is another instance of myself stop it and continue
// my execution don't forget the '-n' option to open or I won't start
NSString *appBundleID = [[NSBundle mainBundle] bundleIdentifier];
NSArray *apps = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication* app in apps)
{
if ([[app bundleIdentifier] isEqual: appBundleID] &&
![app
isEqual: [NSRunningApplication currentApplication]])
{
[app
terminate];
}
}
}
return self;
}