Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 688
DrWurm Avatar asked Sep 04 '12 17:09

DrWurm


2 Answers

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.

like image 172
Chuck Avatar answered Nov 11 '22 09:11

Chuck


Unfortunately you cannot currently generate NSNumber constants in the same way you can generate NSString constants. When you try to do you will get a compiler error

NSNumber * const kNumberConstant = @2; // This doesn't work.

However, you can use primitives instead.

NSInteger const kSomeIntValue = 10;
like image 16
DHamrick Avatar answered Nov 11 '22 10:11

DHamrick