1.当static关键字修饰局部变量时,只会初始化一次且在程序中只有一份内存;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self test];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"---------- viewWillAppear -------------");
[self test];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"---------- viewDidAppear -------------");
[self test];
}
- (void)test {
NSString *normalString;
static NSString *staticString;
NSLog(@"normal = %p, static = %p", &normalString, &staticString);
}
@end
总计:3个输出的内存空间为同一个
2.关键字static不可以改变局部变量的作用域,但可延长局部变量的生命周期(直到程序结束才销毁)。
static NSInteger age;
3.static关键字修饰全局变量:
当static关键字修饰全局变量时,作用域仅限于当前文件,外部类是不可以访问到该全局变量的(即使在外部使用extern关键字也无法访问)。
4.extern关键字:
想要访问全局变量可以使用extern关键字(全局变量定义不能有static修饰)。
liming