1

以下applescriptを使用してファインダーアプリケーションを再起動しています。

osascript -e "tell application \"Finder\"" -e "delay 1" -e "try" -e "quit" -e "delay 1" -e "activate" -e "end try" -e "end tell"  

ただし、このスクリプトがファインダー アプリケーションを再起動しない場合があります (ファインダー アプリケーションを終了するだけです)。コンソールでエラーが発生しません。
http://www.cocoabuilder.com/archive/cocoa/113654-nsapplescript-buggy.html
誰か助けてくれませんか?

4

2 に答える 2

4

Cocoa を使用している場合、これは間違った方法です。AppleScript を構築して実行するシェル スクリプトを呼び出そうとしているのに対し、可能な場合は常にネイティブ API を使用する必要があります。AppleScript は再起動を試みる前に 1 秒間待機しますが、これは任意の値です。実際には、Finder が終了するのを待っている必要があります。

代わりに、NSRunningApplicationKey-Value Observing を使用してインスタンスのterminatedプロパティを監視し、終了時にアプリを再起動できるように、クラスを使用してこれを管理する必要があります。

//assume "finder" is an ivar of type NSRunningApplication
//it has to be a strong reference or it will be released before the observation method
//is called

- (void)relaunchFinder
{
    NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.finder"];
    if([apps count])
    {
        finder = [apps objectAtIndex:0];
        [finder addObserver:self forKeyPath:@"isTerminated" options:0 context:@"QuitFinder"];
        [finder terminate];
    }

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == @"QuitFinder")
    {
        if([keyPath isEqualToString:@"isTerminated"])
        {
            [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@"com.apple.finder" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:NULL launchIdentifier:NULL];
            [object removeObserver:self forKeyPath:@"isTerminated"];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
于 2012-04-19T11:21:47.043 に答える
4

これがアップルスクリプトの方法です。これまで見てきたように、特定の遅延時間に依存することはできません。したがって、実行中のプロセスのリストにあるかどうかを確認して、Finder が終了するのを手動で待ちます。リストに表示されなくなったら、終了したことがわかり、再度アクティブ化できます。

また、繰り返しループがあるため、スクリプトにタイム チェックを入れたことにも注意してください。何か問題が発生した場合に備えて、繰り返しループを永遠に実行したくありません。そのため、10 秒以上実行されると、繰り返しループを自動的に終了します。

tell application "Finder" to quit

set inTime to current date
repeat
    tell application "System Events"
        if "Finder" is not in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "Finder" to activate

これがそのコードの osascript バージョンです。

/usr/bin/osascript -e 'tell application "Finder" to quit' -e 'set inTime to current date' -e 'repeat' -e 'tell application "System Events"' -e 'if "Finder" is not in (get name of processes) then exit repeat' -e 'end tell' -e 'if (current date) - inTime is greater than 10 then exit repeat' -e 'delay 0.2' -e 'end repeat' -e 'tell application "Finder" to activate'
于 2012-04-19T15:03:27.157 に答える