I’m declaring:
static NSString *a = @"a";
and this is a correct declaration in iOS6 (it should be more correct to use the compiler version but I do not know it at the moment). I thought that with number literals also:
static NSNumber *b=@1;
could be a valid declaration. Compiler tells me that initializer element is not a compile time constant. This surprises me a bit. Since NSNumber is immutable as NSString and since I’m using a literal as in string case, I thought it could be valid as well.
Does anybody have a reasonable explanation about this difference?
The first line is a compile-time constant since you are assigning
@"a"and not something likestatic NSString *a = [NSString stringWithFormat:@"a"];(That will throw the same error)But for an
NSNumber,static NSNumber *b = @1;is actually equivalent tostatic NSNumber *b = [NSNumber numberWithInt:1];. For more details check Objective-C Literals.Note that in the above case, the right side is not a compile-time constant. It is an expression that must be evaluated at runtime. In C and Objective-C, static variables must be initialized with compile-time constants.
If you want to have
NSNumberas aconstyou can check with the approaches mentioned here Objective C – How to use extern variables?.Also check this on Objective C literals from Mike Ash,
And,