I am trying to use extern variables.
It complains that because of using numberWithInt I am not passing a contants as the value of my variable
So I removed the const and it's complaining that an extern variable must be a constant, so what is the solutions here?
I DO NOT WANT TO USE INT
.h
extern NSNumber const *MoveID;
.m
NSNumber const *MoveID = [NSNumber numberWithInt:1];
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
Variable Declaration in Objective-C You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your Objective-C program but it can be defined only once in a file, a function or a block of code.
Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.
You can try to do the following:
.h
extern NSNumber *MoveID;
.m
NSNumber *MoveID;
@implementation MYGreatClass
+ (void) initialize {
static bool done = FALSE;
if(!done){ // This method will be called again if you subclass the class and don't define a initialize method for the subclass
MoveID = [[NSNumber numberWithInt:1] retain];
done = TRUE;
}
}
As @BoltClock said, you cannot set a non-constant value to be of const
type.
What you could do is this:
extern NSNumber *MoveID;
And...
NSNumber *MoveID;
@implementation SomeClass
static BOOL loaded = NO;
+ (void) initialize {
if(!loaded) {
MoveID = [[NSNumber alloc] initWithInt:1];
loaded = YES;
}
}
//blah blah blah
@end
EDIT: I just realized that I totally missed the question and was going on about why the error was occurring, oops. I'll leave the first part of my answer here though because Jacob Relkin quotes it in his answer.
Because [NSNumber numberWithInt:1]
is not a compile-time constant value, you cannot set an NSNumber
created with it to a const
variable.
There appears to be a radar about extern NSNumber const
s, which seem to be unsupported in Objective-C. I guess you can use a preprocessor macro to create NSNumber
s from constant ints or floats as described in this article. It's not nearly the same as what you intend but it seems to be pretty close.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With