Search code examples
objective-ciosconstantsnsnumber

NSNumber constants in Obj-C


I want to make some NSNumber constants via the same style used for NSStrings in this topic. That is, I'm creating separate constants.h/.m files and importing them into classes that need to access them.


Solution

  • The trouble with doing this is that there isn't such a thing as a compile-time constant NSNumber. Only NSString gets that distinction. NSNumbers are always created dynamically. You can fake it by using a function that runs at your program's startup to initialize the variables. Your options:

    1. Create a class with a +load method that performs the initialization.

    2. In the file with the constants, include a function with __attribute__((constructor)). So, for example:

      // Constants.m
      
      NSNumber *someGlobalNumber;
      
      __attribute__((constructor))
      static void InitGlobalNumber() {
          someGlobalNumber = [[NSNumber numberWithInteger:1] retain];
      }
      

    But of course then you can't reliably use these numbers in any other functions which are run that early in the startup process. This usually isn't a problem, but is worth keeping in mind.

    The other option, which I've seen crop up a few times, is to have a class with accessors for the numbers instead of giving raw access to the variables. It's a bit of a heavier design, but it also feels less voodooish, which has its charms.