extern關鍵字
原來經常看到extern關鍵字,但是一直搞不懂具體的用法,以及跟static的區別。今天就要搞懂它~~~
1.首先隨便先一個類Foo,并在頭文件里添加extern NSString * const fooExtern;
Foo.h
#import <Foundation/Foundation.h>
extern NSString * const fooExtern;
@interface Foo : NSObject
@end
- 這里
不能定義
,否則會報錯(static
關鍵字是可以的,如:static NSString * const str = @"ahaha";
)- 如果我只聲明不定義,然后在外部使用
fooExtern
會怎樣?編譯會報錯~
。說明這里的extern只是聲明,必須在別的地方定義
2.然后Foo.m里定義,寫在哪呢?
- 剛開始我并不知道怎么用,寫在了某個方法里,如下:
#import "Foo.h"
@implementation Foo
- (instancetype)init {
if (self = [super init]) {
NSString * const fooExtern = @"haha";
}
return self;
}
@end
結果:外部調用時會報錯的
- 正確的寫法,如下:
#import "Foo.h"
NSString *const fooExtern = @"hhaa";
@implementation Foo
@end
- 外部調用的寫法:如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(@"extern: %@", fooExtern);
}
fooExtern的定義寫在viewControler里也是可以,因為extern NSString * const fooExtern;只是聲明有一個fooExtern,定義在哪個地方都可以