How to get the executable path of a command line tool in Objective C (Foundation framework)?
I'm trying to work out a way to identify the executable path of a command line t开发者_如何学运维ool in Objective C.
Hence, if the executable is /Applications/Utils/MyTool, then that method would return /Applications/Utils
I'm using the Foundation framework.
Call me a purist - or a bundle-hater - if you must.. but I "like"
NSString *myLittleCLIToolPath = NSProcessInfo.processInfo.arguments[0];
I'm assuming that by /Applications/Utils/MyTool
, you mean an application named "MyTool" in the "Utils" directory within the "Application" directory (which is actually the path /Applications/Utils/MyTools.app
). In that case, you could get the directory in which the application resides (/Applications/Utils
) with the following bit of code:
NSString *appParentDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
Here's a Swift version of @mipadi's answer:
let appParentDirectory = Bundle.main.bundleURL.deletingLastPathComponent()
Documentation: Bundle.main.bundleURL.deletingLastPathComponent()
And of @AlexGray's answer:
let myLittleCliToolPath = ProcessInfo.processInfo.arguments.first
Documentation: ProcessInfo.processInfo.arguments.first
Note that this one results in an optional string. It's likely that you got the path successfully, but not 100% guaranteed, so you could also use one of these as a backup (which also return optionals) if you have access to AppKit, or the aforementioned Bundle
approach (which does not):
NSRunningApplication.current.bundleURL?.deletingLastPathComponent()
Documentation: NSRunningApplication.current.bundleURL.deletingLastPathComponent()
NSRunningApplication.current.executableURL?.deletingLastPathComponent()
Documentation: NSRunningApplication.current.executableURL.deletingLastPathComponent()
精彩评论