I found this question that explains very well how to declare a constant NSString
or primitive type in Objective-C. The method worked perfectly.
I ran into a problem when, recently, I was writing an application using CoreBluetooth. There are several CBUUID
's that I'd like to save as constants because I will be using them frequently. In this case the FOUNDATION_EXPORT
technique fails.
When I put this in my header file
FOUNDATION_EXPORT CBUUID *const _Nonnull kTxPowerServiceUUID;
and this in my .m file
CBUUID *const kTxPowerServiceUUID = [CBUUID UUIDWithString:@"1804"];
I get this error
ERROR: Initializer element is not a compile-time constant.
To my surprise, I get this error even when the object I am trying to initialize is a compile time constant. For example, I have several calculations in my application that involve the speed of light in meters per second. I tried creating a constant NSNumber
to represent it. When I tried this
NSNumber *const kTheSpeedOfLight = @(299792458);
I got the same error, and resorted to declaring kTheSpeedOfLight
as an unsigned int
.
So is there a way to create constants from objects in general? Or is it just for primitives and NSString
's?