How to relaunch finder application

前端 未结 2 1417
我寻月下人不归
我寻月下人不归 2021-01-07 10:51

I am using following applescript to relaunch finder application.

osascript -e \"tell application \\\"Finder\\\"\" -e \"delay 1\" -e \"try\" -e         


        
2条回答
  •  难免孤独
    2021-01-07 11:25

    This is the wrong way to go about things if you are using Cocoa. You should always use native APIs where possible, whereas you are attempting to call a shell script that itself builds and runs an AppleScript. Your AppleScript waits for one second before attempting a relaunch, which is an arbitrary value. You should actually be waiting for Finder to quit.

    Instead, you should use the NSRunningApplication class to manage this, by using Key-Value Observing to monitor the instance's terminated property, so that you can relaunch the app when it terminates:

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

提交回复
热议问题