日々精進

新しく学んだことを書き留めていきます

Macアプリをプログラムから再起動する方法

シェルスクリプトを実行して自プロセスをKillしてOpenすればよい。

    NSString *killArg1AndOpenArg2Script = @"kill -9 $1 \n open \"$2\"";
    NSString *ourPID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
    NSString * pathToUs = [[NSBundle mainBundle] bundlePath];

    // -c tells sh to execute the next argument, passing it the remaining arguments.
    NSArray *shArgs = [NSArray arrayWithObjects:@"-c",
                                                killArg1AndOpenArg2Script,
                                                @"", //$0 path to script (ignored)
                                                ourPID, //$1 in restartScript
                                                pathToUs, //$2 in the restartScript
                                                nil];
    NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
    [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
    NSLog(@"*** ERROR: %@ should have been terminated, but we are still running", pathToUs);
    assert(!"We should not be running!");

参考:Restarting Your Mac OS X Cocoa Application « Vincent Gable’s Blog