Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

tags - Why can I not use my constant in the switch - case statement in Objective-C ? [error = Expression is not an integer constant expression]

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

I have Constants.h with the following:

// Constants.h    
extern NSInteger const TXT_NAME;

And Constants.m as:

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

NSInteger const TXT_NAME        = 1;

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;
        }
    }
}

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

  • Expression is not an integer constant expression
  • Case label does not reduce to an integer constant

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

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

Update:

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.

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

#define TXT_NAME 1

Or even better, like this:

enum {TXT_NAME = 1};


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...