问题
We know that Xcode maintains environment variable of ${TARGET_NAME}
but how to access this variable in objective-C code ?
What I have tried ?
I have added "TARGET_NAME=${TARGET_NAME}"
this in Preprocessor macros section of Build Settings. But now I am not sure how to use this variable "TARGET_NAME"
as a string in objective-C code.
In my case product name and target name are different so, no chance to use that.
I tried to access using
#ifdef TARGET_NAME
NSLog(@"TargetIdentifier %@",TARGET_NAME);
#endif
This code is giving error like "Use of undeclared identifier 'myapptargetname'"
回答1:
You can add "TargetName" key to your Info.plist file:

Then you can access it (swift code):
var plistFileName = NSBundle.mainBundle().infoDictionary?["TargetName"] as String
回答2:
NSLog(@"Target name: %@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]);
Hope to help you!
Edited: "CFBundleName" thanks Max and Daniel Bo for your commend
回答3:
Swift 4, Xcode 9+
Bundle name:
Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? ""
Bundle display name:
Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? ""
Swift 3, Xcode 8+
let targetName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
回答4:
In Xcode 7.3.1
if let targetName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String{
print(targetName)
}
回答5:
I must credit the original answer by vk.edward.li, as this answer only merely expands on it.
All the build setting macros can easily be used in source code as preprocessor macros too. The problem is that they're not set in advance; you have to specify which ones you get access to, yourself.
I've already added three extra preprocessor macros. Simply click the +
, and add this: TARGET_NAME=\""$TARGET_NAME"\"
, and you've granted yourself access to one more build setting macro.
Project settings ––> Build Settings ––> Apple Clang - Preprocessing[Preprocessor Macros]
. Note that if you try to insert them for both compilation modes at once, the DEBUG=1
macro will get deleted, but it can as easily be added right back afterwards.
It's also worth noting that the macro values should be set differently for different languages: Objective-C
and C++
/Swift
, etc. This is due to the NSString
prefix used in Objective-C
, so for that language, it should be MACRO=@\""$MACRO"\"
instead of MACRO=\""$MACRO"\"
.
来源:https://stackoverflow.com/questions/18783055/how-to-get-target-name