objective-c - iPhone : access constant values

标签 objective-c ios cocoa-touch constants

我已经定义了一些常量,比如

#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。您可以在代码中使用它。

比如我添加了一个文件。这显示了脚本的正确使用。

enter image description here

关于objective-c - iPhone : access constant values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14030071/

相关文章:

ios - 上传图片到服务器时无法显示进度条

php - 如何使用警报 View 单击按钮来更新 sql 中的值?

ios - 期望参数类型为整数,但获取的是 id

iphone - 如何从委托(delegate)访问 UITableView?

cocoa-touch - UISegmentedControl 不随 super View 缩放

objective-c - NSComboBoxDelegate 被调用,但旧的 'stringValue' 仍然存在

ios - Swift - 在没有 Storyboard initWithFrame 错误的情况下创建 collectionView

ios - 将循环、连续的 UISlider 值转换为计数器

ios - 记住 tableView 中选定的单元格

objective-c - 自动包含@2x 图像(视网膜支持)