我已经定义了一些常量,比如
#define val_a @"A"
#define val_b @"B"
#define val_c @"C"
现在我有一些与我定义的常量同名的键,我想打印常量的值(不使用常量键)。我试过了,
- (NSString *) actualValForKey:(NSString *)key
{
return key; //It will return **key** parameter, but I want to return the **constant value** as defined
}
我可以这样写 NSLog(@"Value = %@", [self actualValForKey:keys]);
因为所有的键都是动态的,我不能写 NSLog(@ "Value = %@", val_a);
这样。
这里,keys
将作为 NSString
出现。
附言不断的识别。
这可能吗?替代方案?
最佳答案
在 C++/ObjectiveC 中,您无法在运行时获取宏的名称。因为,宏名称被替换为宏体的副本。
您可以阅读文档 here
The #define directive is typically used to associate meaningful identifiers with constants, keywords, and commonly used statements or expressions. Identifiers that represent constants are sometimes called "symbolic constants" or "manifest constants." Identifiers that represent statements or expressions are called "macros." In this preprocessor documentation, only the term "macro" is used. When the name of the macro is recognized in the program source text or in the arguments of certain other preprocessor commands, it is treated as a call to that macro. The macro name is replaced by a copy of the macro body. If the macro accepts arguments, the actual arguments following the macro name are substituted for formal parameters in the macro body. The process of replacing a macro call with the processed copy of the body is called "expansion" of the macro call.
但是,如果你真的需要。您可以编写构建脚本,它解析文件中的所有 #define
指令并创建一个 NSDictionary。您可以在代码中使用它。
比如我添加了一个文件。这显示了脚本的正确使用。
关于objective-c - iPhone : access constant values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14030071/