2011-02-19 75 views
8

使用命令行启动Path Finder应用程序时,我使用open -a Path Finder.app /Users/。 基于这个想法,我使用下面的代码来启动Path Finder。使用Objective-C/Cocoa启动Mac应用程序

我可以使用启动应用程序而不使用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]; 

回答

24
if(![[NSWorkspace sharedWorkspace] launchApplication:@"Path Finder"]) 
    NSLog(@"Path Finder failed to launch"); 

随着参数:

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 

你也可以使用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]; 
+0

如何给参数? – prosseek 2011-02-19 05:07:13

3

基于娱记在different posting答案,NSWorkspace是使用工具,我可以只用两行代码得到同样的结果。

openFile可用于将参数传递到Path Finder,通常是目录,而不是文件。但是,它工作正常。

[[NSWorkspace sharedWorkspace] openFile:string2 withApplication:@"Path Finder"]; 
[[NSApplication sharedApplication] terminate:nil]; 
+0

这不会工作,它的_parameter_不是一个文件,而是一个**参数**的应用 – Shebuka 2012-07-20 17:03:11