为什么我不能在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]

查看:470
本文介绍了为什么我不能在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.m中则不需要任何内容​​.

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

甚至更好,例如:

enum {TXT_NAME = 1};

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

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