Constants by another name

Firstly, I saw this question and understand why the following code does not work. This is not my question.

I have a constant that is declared as:

//Constants.h extern NSString * const MyConstant; //Constants.m NSString * const MyConstant = @"MyConstant"; 

However, in some contexts it is more useful to have this constant with a much more descriptive name, for example MyReallySpecificConstant . I was hoping to do:

 //SpecificConstants.h extern NSString * const MyReallySpecificConstant; //SpecificConstants.m #import "Constants.h" NSString * const MyReallySpecificConstant = MyConstant; 

Obviously, I cannot do this (which is explained in the related question above).

My question is:

How else (besides something like #define MyReallySpecificConstant MyConstant ) can I provide one constant under several names?

+6
c objective-c constants
source share
3 answers

In general, the compiler dumps identical string constants to the same string, unless you say so. Even if you cannot initialize one constant with another, initializing both of them with the same value will have the same network effect.

 //Constants.h extern NSString * const MyConstant; extern NSString * const MyOtherConstant; //Constants.m #define MyConstantValue "MyConstant" NSString * const MyConstant = @MyConstantValue; NSString * const MyOtherConstant = @MyConstantValue; 

You hide #define in one source file, not in the header. You need to change the value in only one place. You have two names for one constant. Of course, in your scenario with constants defined in several files, you should have #define available for these source files.

+6
source share

My first reaction to your question was a question in return - is the fact that you want to have a constant under several names an indicator that the name of a constant needs to be rethought in the first place?

+4
source share

Assign your string constants in code:

 //Constants.h extern NSString * MyConstant; extern NSString * MyOtherConstant; void setUpConstants(); //Constants.m NSString * MyConstant; NSString * MyOtherConstant; NSString * const ValueOfString = @"A Value"; void setUpConstants() { MyConstant = ValueOfString; MyOtherConstant = ValueOfString; } 

One drawback if they are not protected by the compiler from modification. However, initialization is very flexible, and you may be able to improve other code. You also guarantee different addresses for your lines, regardless of whether the compiler decides that folding is what it does this week.

+2
source share

All Articles