为什么我不能在 Objective-C 的 switch-case 语句中使用我的常量?[错误 = 表达式不是整数常量表达式] [英] Why can I not use my constant in the switch - case statement in Objective-C ? [error = Expression is not an integer constant expression]

查看:27
本文介绍了为什么我不能在 Objective-C 的 switch-case 语句中使用我的常量?[错误 = 表达式不是整数常量表达式]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have an issue with using a constant variable in the following switch statement in Objective-C.

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

I have Constants.h with the following:

// Constants.h    
extern NSInteger const TXT_NAME;

Constants.m 为:

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

NSInteger const TXT_NAME        = 1;

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

Then in TabBasic.m I am trying to use this constant in a switch-case statement:

// 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:"行上给了我以下两个错误:

But unfortunately it is giving me the following two errors on the "case TXT_NAME:" line:

  • 表达式不是整数常量表达式
  • 案例标签不会缩减为整数常量

有谁知道我做错了什么?UITextField 的tag"变量返回一个 NSInteger,所以我看不到问题...

Does anyone know what I'm doing wrong? The "tag" variable of a UITextField returns an NSInteger, so I don't see the issue...

感谢您的帮助!

推荐答案

快速解决方案,你应该把NSInteger const TXT_NAME = 1;放在Constants.h中,Constants中什么都不需要.米.

Quick solution, you should place NSInteger const TXT_NAME = 1; in Constants.h, and don't need anything in Constants.m.

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

Reason: If you set the value of the constant in the .m, it is not visible by other translation units that only include the .h file. The value of the constant must be known at compile time to be able to be used in a case within a switch.

更新:

在 Objective-C++ 中编译时,上述方法有效.您需要让文件以 .mm 而不是 .m 结尾,以便它们在 Objective-C++ 而不是 Objective-C 中编译.

The above works when compiling in Objective-C++. You need to have your files end in .mm instead of .m for them to be compiled in Objective-C++ instead of Objective-C.

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

In order to work in Objective-C, you should define your constant either like this:

#define TXT_NAME 1

或者更好,像这样:

枚举 {TXT_NAME = 1};

这篇关于为什么我不能在 Objective-C 的 switch-case 语句中使用我的常量?[错误 = 表达式不是整数常量表达式]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆