Mac OS X:如何从“命令行工具"启动应用程序(.app).应用类型?
在Xcode 4.6中,我基于命令行工具"项目模板创建了一个新应用程序.
In Xcode 4.6, I created a new application based on the "Command Line Tool" project template.
如何从该命令行工具"应用程序中以编程方式启动另一个应用程序(.app应用程序包)?
How can I programmatically start another application (.app application bundle) from that "Command Line Tool" app?
使用Launch Services和NSWorkspace
有很多方法可以完成此任务.
There are numerous ways to accomplish this, using Launch Services and or NSWorkspace
.
标识捆绑应用程序的一种更灵活的方法是通过其捆绑标识符(CFBundleIdentifier
),捆绑标识符是类似于com.apple.TextEdit
的字符串.这使您可以识别应用程序,而不必硬编码将找到该应用程序的假定路径,也无需硬编码应用程序捆绑包的名称,而这两种用户都可以轻松更改.您可以使用NSWorkspace
的
One of the more flexible ways to identity a bundled application is via its bundle identifier (CFBundleIdentifier
), which is a string like com.apple.TextEdit
. This allows you to identify an application without having to hard-code an assumed path where the application will be found, or by hard-coding the name of the application bundle, both of which a user could easily change. You can use NSWorkspace
's launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier:
to launch the app. If you don't already know it, you can obtain the bundle identifier of an application bundle by checking its AppName.app/Contents/Info.plist
file. Then use the following code:
if (![[NSWorkspace sharedWorkspace]
launchAppWithBundleIdentifier:@"com.apple.TextEdit"
options:NSWorkspaceLaunchDefault
additionalEventParamDescriptor:NULL
launchIdentifier:NULL]) {
NSLog(@"launching app failed!);
}
重要提示:NSWorkspace
是AppKit.framework
框架的一部分,该框架最初并未包含在命令行工具"项目模板中.要将其添加到您的项目中,请在目标列表中选择目标,如下图所示,然后单击+按钮以添加其他框架.
Important: NSWorkspace
is part of the AppKit.framework
framework, which is not initially included in the "Command Line Tool" project template. To add it to your project, select the target in the list of targets like shown in the image below, and click the + button to add additional frameworks.
同时添加AppKit.framework
和Cocoa.framework
.
这将导致所有3个文件都在与库链接二进制文件"步骤中列出.此时,您可以从链接阶段删除Foundation.framework
和AppKit.framework
,而仅保留Cocoa.framework
,如下所示:
That will result in all 3 being listed in the Link Binary With Libraries step. At that point, you can remove both the Foundation.framework
and AppKit.framework
from the linking stage, and leave just the Cocoa.framework
, like below: