简体   繁体   English

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

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

I have an Xcode project with several targets.我有一个包含多个目标的 Xcode 项目。 Let's say the target names are AppFreeVersion and AppPaidVersion .假设目标名称是AppFreeVersionAppPaidVersion They share the same codebase, but I want to implement some logic that is only for one of the targets.它们共享相同的代码库,但我想实现一些仅适用于其中一个目标的逻辑。

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 question requires me to pass an environment variable in the build setting, which I don't want to do.这个问题中给出的解决方案要求我在构建设置中传递一个环境变量,我不想这样做。

How about adding ${TARGET_NAME} in your info.plist?在 info.plist 中添加${TARGET_NAME}怎么样?

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

Swift 3.0 Solution. Swift 3.0 解决方案。

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

The accepted answer by Niko is still working for me on Xcode 12.2 and iOS 14.2 Niko 接受的答案仍然适用于 Xcode 12.2 和 iOS 14.2

Here is a screenshot to better clarify what needs to be done in Info.plist :这是一个屏幕截图,可以更好地阐明需要在Info.plist完成的操作:

Info.plist 截图

You need to do this for each target's corresponding Info.plist您需要为每个目标的相应Info.plist执行此操作

You don't even need to use $(TARGET_NAME) as the value, you can give your own custom unique values and check for those instead.您甚至不需要使用$(TARGET_NAME)作为值,您可以提供自己的自定义唯一值并检查这些值。

First you have to add the target name property in the .plist file of respective target.首先,您必须在相应目标的 .plist 文件中添加目标名称属性。 then you can get it anywhere in the code.然后你可以在代码的任何地方获取它。

print("Target Name = " + (Bundle.main.infoDictionary?["TARGET_NAME"] as! String))

enter image description here在此处输入图片说明

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"]

在 Swift 4.0 上

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM