I have a global constant:
FOUNDATION_EXPORT NSString *const ENGModelItemText; // .h file
NSString *const XYZConstant1 = @"XYZConstant1"; // .m file
… and I would like to create XYZConstant2 that would point to XYZConstant1. I thought it would be as simple as this:
NSString *const XYZConstant2 = &XYZConstant1
I played with * and & a bit but can’t get it right. I’d like to get rid of #define for XYZConstant2 that I use now.
You cannot create a compile-time alias like this in C (and therefore in ObjC). You can create a runtime alias by declaring
XYZConstant2inside of a function or method, but not as a static. Compare this pure C, which creates the same error:(See also Compiler error: "initializer element is not a compile-time constant".)
Typically when this kind of aliasing is required (usually because a string constant was renamed), you use a
#define(much as I hate defines).That said, you should not rely on the fact that two object pointers are the same address unless you mean “it is this object” rather than “it has this value.” (And you never mean that for strings because strings only have value.) Write to the semantics, not the implementation details. Don’t prematurely optimize comparisons.