如何获取当前在 Xcode 中运行的目标的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36758639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:45:00  来源:igfitidea点击:

How do I get the name of the target that is currently running in Xcode?

iosxcodebuild

提问by Enrico Susatyo

I have an Xcode project with several targets. Let's say the target names are AppFreeVersionand AppPaidVersion. They share the same codebase, but I want to implement some logic that is only for one of the targets.

我有一个包含多个目标的 Xcode 项目。假设目标名称是AppFreeVersionAppPaidVersion。它们共享相同的代码库,但我想实现一些仅适用于其中一个目标的逻辑。

Without modifying my scheme or build settings, is there a way to get the string of my current target name? The solution given in this questionrequires me to pass an environment variable in the build setting, which I don't want to do.

在不修改我的方案或构建设置的情况下,有没有办法获取我当前目标名称的字符串?这个问题中给出的解决方案要求我在构建设置中传递一个环境变量,我不想这样做。

采纳答案by Niko Adrianus Yuwono

How about adding ${TARGET_NAME}in your info.plist?

添加${TARGET_NAME}您的 info.plist 怎么样?

And I guess you already know how to get it

我猜你已经知道如何获得它

Obj-C

对象-C

[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];

Swift

迅速

let targetName = NSBundle.mainBundle().infoDictionary?[key_name] as String

回答by Abo3atef

Swift 3.0 Solution.

Swift 3.0 解决方案。

func getTargetName() -> String {
    return Bundle.main.infoDictionary?["CFBundleName"] as! String
}

回答by SaRaVaNaN DM

Just set Target name in your Scheme -> Environment Variables -> add Name and Value. eg: targetName = "mytesttarget"

只需在您的方案中设置目标名称 -> 环境变量 -> 添加名称和值。例如:targetName = "mytesttarget"

Obj-c

对象-c

NSDictionary* envir = [[NSProcessInfo processInfo] environment];

NSDictionary* envir = [[NSProcessInfo processInfo] environment];

NSString* targetName = envir[@"targetName"];

NSString* targetName = 环境[@"targetName"];

Swift

迅速

let envir = NSProcessInfo.processInfo().environment

让环境 = NSProcessInfo.processInfo().environment

let targetName = envir["targetName"]

让 targetName = 环境 ["targetName"]

回答by juanram0n

On Swift 4.0

在 Swift 4.0 上

let targetName = Bundle.main.infoDictionary?["TargetName"] as! String