2011-09-03 54 views
17

我见过两种创建全局变量的方法,有什么区别,以及你什么时候使用它们?“extern const”vs“extern”only

//.h 
extern NSString * const MyConstant; 

//.m 
NSString * const MyConstant = @"MyConstant"; 

//.h 
extern NSString *MyConstant; 

//.m 
NSString *MyConstant = @"MyConstant"; 

回答

32

前者是理想的常量,因为字符串它指向不能被改变:

//.h 
extern NSString * const MyConstant; 

//.m 
NSString * const MyConstant = @"MyConstant"; 
... 
MyConstant = @"Bad Stuff"; // << YAY! compiler error 

and 

//.h 
extern NSString *MyConstant; 

//.m 
NSString *MyConstant = @"MyConstant"; 
... 
MyConstant = @"Bad Stuff"; // << NO compiler error =\ 
总之

,使用const的(前)在默认情况下。编译器会让你知道你是否试图改变它 - 然后你可以决定是否代表你的错误,或者它指向的对象可能会改变。这是一个很好的保护措施,可以节省大量的错误/头疼。

的其他变型为值:

extern int MyInteger; // << value may be changed anytime 
extern const int MyInteger; // << a proper constant