0

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?

Community
  • 1
  • 1
William Rosenbloom
  • 2,506
  • 1
  • 14
  • 37
  • 1
    There is special compiler support for embedding `NSString`s in the compiled binary. All other declarations are translated into object creation calls, so `@(int)` is translated into `[NSNumber numberWithInt:int]`. This is not a constant. – Avi Apr 20 '16 at 03:44
  • try declare in the header, extern const CBUUID *const _Nonnull kTxPowerServiceUUID; then in a .m file somewhere const CBUUID *const kTxPowerServiceUUID = [CBUUID UUIDWithString:@"1804"];; – Jigar Apr 20 '16 at 03:46
  • 1
    @DarjiJigar That won't work. That will still give the same "not a compile time constant" error. – rmaddy Apr 20 '16 at 03:47
  • @DarjiJigar I can confirm what rmaddy said. Just tried it. Didn't work. – William Rosenbloom Apr 20 '16 at 03:49
  • @WilliamRosenbloom try to create function for declare the vale than after access the variable – Jigar Apr 20 '16 at 03:50
  • @rmaddy Thanks for marking this as a duplicate. That other question was really helpful. – William Rosenbloom Apr 20 '16 at 03:57
  • `NSNumber *const kTheSpeedOfLight = @(299792458);` This line is working perfect.... – Mubin Mall Apr 20 '16 at 04:15

0 Answers0