Objective C - 如何使用extern变量?

11
我正在尝试使用外部变量。因为我使用了“numberWithInt”,所以它抱怨我没有将常量作为我的变量值传递。因此,我去掉了“const”,但现在它又抱怨说外部变量必须是一个常量。那么,这里有什么解决方案呢?我不想使用int。
.h
extern NSNumber const *MoveID;

.m
NSNumber const *MoveID = [NSNumber numberWithInt:1];
4个回答

15

您可以尝试以下操作:

.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;
    }
}

7
请注意,只有当某个地方触及MYGreatClass类时,MoveID的值才会被设置。如果这是一个问题,您可以使用+load方法。 - bbum

3

正如@BoltClock所说,您不能将非常量值设置为const类型。

您可以这样做:

extern NSNumber *MoveID;

并且...

NSNumber *MoveID;
@implementation SomeClass 
static BOOL loaded = NO;
+ (void) initialize {
   if(!loaded) {
      MoveID = [[NSNumber alloc] initWithInt:1];
      loaded = YES;
   }
}
//blah blah blah

@end

2
编辑:我刚意识到我完全错过了问题,一直在讲错误发生的原因,糟糕。不过我会把我的回答的前半部分留在这里,因为Jacob Relkin在他的回答中引用了它。

因为[NSNumber numberWithInt:1]不是编译时常量值,所以您不能将使用它创建的NSNumber设置为const变量。

似乎有一个关于extern NSNumber constradar,在Objective-C中似乎不支持它们。我想你可以使用预处理器宏从常量int或float创建NSNumber,如本文中所述。虽然这与您的意图不完全相同,但它似乎非常接近。


0

仅为完整起见,现代方法是这样做:

在 .h 文件中

extern NSNumber *MoveID;

in .m

NSNumber *MoveID;

...

- (void)viewDidLoad {
    [super viewDidLoad];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        MoveID = @1;
    });

    ...
}

dispatch_once() 只会运行一次,因此初始化程序不会重复,并且它是线程安全的。此外,将初始化代码下推到视图生命周期的较低位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接