使用Objective-C/Cocoa启动Mac应用程序

pro*_*eek 8 cocoa objective-c launching-application

使用命令行启动Path Finder应用程序时,我会使用open -a Path Finder.app /Users/.基于这个想法,我使用以下代码来启动Path Finder.

我可以不使用open命令行启动应用程序吗?

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/open"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-a", @"Path Finder.app", @"/Users/", nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];
Run Code Online (Sandbox Code Playgroud)

ugh*_*fhw 26

if(![[NSWorkspace sharedWorkspace] launchApplication:@"Path Finder"])
    NSLog(@"Path Finder failed to launch");
Run Code Online (Sandbox Code Playgroud)

带参数:

NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSURL *url = [NSURL fileURLWithPath:[workspace fullPathForApplication:@"Path Finder"]];
//Handle url==nil
NSError *error = nil;
NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
[workspace launchApplicationAtURL:url options:0 configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
//Handle error
Run Code Online (Sandbox Code Playgroud)

您还可以使用NSTask传递参数:

NSTask *task = [[NSTask alloc] init];
NSBundle *bundle = [NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"Path Finder"]]];
[task setLaunchPath:[bundle executablePath]];
NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
[task setArguments:arguments];
[task launch];
Run Code Online (Sandbox Code Playgroud)

  • @rocky您无法直接访问字典,但存储在字典中的参数将作为命令行参数传递,因此您可以在主函数中使用`argc`和`argv`. (2认同)