I am trying to use exte开发者_StackOverflow中文版rn 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];
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.
Just for completeness, the modern method is do do it as:
in .h
extern NSNumber *MoveID;
in .m
NSNumber *MoveID;
...
- (void)viewDidLoad {
[super viewDidLoad];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
MoveID = @1;
});
...
}
dispatch_once()
will only ever run once so the initialiser is not duplicated, and it is thread safe. Also, pushing down initialisation code lower down in the view lifecycle.
精彩评论