1.宏,不要使用,它只是一个预处理命令,可以重复定义的
#define name @"string"
#define name @"aaa"
Xcode会出现提示
'name' macro redefined
它的值永远是最后一次赋值的结果
2.全局常量
在@implementation外定义
NSString * const str = @"string1";
3.全局变量
(1).extern
在ViewController.h中声明
//声明
extern const NSString *extraString;
extern修饰,意味着该变量可扩展
在使用时,定义同名变量即可得到它的值
//使用时,定义同名变量
const NSString *extraString;
(2).static
在OC文件ViewController.h或.m中定义一个变量
//变量
static NSString * staticString = @"This is static string";
//类方法,用于获取变量
+(NSString *)getStaticString;
//实现
+(NSString *)getStaticString{
return staticString;
}
OC中static修饰的变量和JAVA中的静态变量是一样的,只是OC中无法通过类名直接访问变量,我们定义类方法就可以了
//使用
NSString * a = [ViewController getStaticString];
注:
你可能注意到 全局变量和常量里 const 放的位置不同,这里区分一下:
//第一种,这里const修饰的是指针,所以指针本身是不会变的,指向的地址可以变,即 常量指针;所有说要全局变量就找你了,相当于固定的盒子,合适的就放里面
const NSString * str = @"aaa";
//第二种,这个和第一种不是一样的意思嘛
NSString const *str = @"bbb";
//第三种,这里就不一样了,人家是指针常量,值不能变,所以有做全局常量的潜质
NSString * const str = @"ccc";