objective-c - 为什么我不能在 Objective-C 的 switch-case 语句中使用我的常量? [错误 = 表达式不是整型常量表达式]

标签 objective-c tags constants case switch-statement

所以我在 Objective-C 的以下 switch 语句中使用常量变量时​​遇到问题。

我的 Constants.h 包含以下内容:

// Constants.h    
extern NSInteger const TXT_NAME;

Constants.m作为:

// Constants.m
#import "Constants.h"

NSInteger const TXT_NAME        = 1;

然后在 TabBasic.m 中,我尝试在 switch-case 语句中使用这个常量:

// TabBasic.m

#import "TabBasic.h"
#import "Constants.h"

... code ...

- (IBAction)saveValue:(id)sender {
    if ([sender isKindOfClass: [UITextField class]]) {
        UITextField *txtField = (UITextField *) sender;

        switch (txtField.tag) {
            case TXT_NAME:
                NSLog(@"Set property name to: %@", txtField.text); 
                break;
        }
    }
}

但不幸的是,它在“case TXT_NAME:”行中给我以下两个错误:

  • 表达式不是整数常量表达式
  • case 标签不归约为整数常量

有谁知道我做错了什么? UITextField 的“标签”变量返回一个 NSInteger,所以我没有看到问题...

感谢您的帮助!

最佳答案

快速解决方案,您应该将 NSInteger const TXT_NAME = 1; 放在 Constants.h 中,并且在 Constants.m 中不需要任何内容​​。

原因:如果在.m中设置常量的值,其他只包含.h文件的翻译单元是看不到的。常量的值必须在编译时已知,以便能够在 switch 内的 case 中使用。

更新:

以上在 Objective-C++ 中编译时有效。你需要让你的文件以 .mm 而不是 .m 结尾,这样它们才能在 Objective-C++ 而不是 Objective-C 中编译。

为了在 Objective-C 中工作,您应该像这样定义常量:

#define TXT_NAME 1

或者更好,像这样:

枚举 {TXT_NAME = 1};

关于objective-c - 为什么我不能在 Objective-C 的 switch-case 语句中使用我的常量? [错误 = 表达式不是整型常量表达式],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6585276/

相关文章:

ios - 如何将整数发送到类型 id 的指针

objective-c - 在 Documents 或 Caches 文件夹中使用 iOS 文件名设备修饰符(~ipad、~iphone)

Jenkins 管道 : when condition and mercurial tags

安卓 NFC : enable and disable the NFC detected sounds

c# - 如何创建包含 const 内容的 C# 列表?

c++ - 当调用来自相同的非 const 版本重载成员函数时,是否可以删除 const 限定符?

objective-c - 如何更改按钮上的背景图像,iOS?

objective-c - 在 iOS 和 Cocoa Touch 上,我们是否应该假设我们应该始终发送 "super"相同的消息?

jQuery/CSS : Making the autocomplete push other divs down?

c++ - 直接将数组写入参数会在 C++ 中出错