修饰局部变量
1、使得局部变量只初始化一次
2、局部变量在程序中只有一份内存
3、局部变量的作用域不变,但是生命周期变了(直到程序结束才销毁)
修饰全局变量
1、全局变量的作用域仅限当前文件
基于以上的几点写了一个实例:
#import "ViewController.h"
static NSString *staticValue2;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 连续调用两次
[self staticTestA];
[self staticTestA];
// 连续调用两次
[self staticTestB];
[self staticTestB];
// 连续调用两次
[self staticTestC];
[self staticTestC];
}
- (void)staticTestA
{
static NSString *staticValue1;
NSLog(@"staticTestA------------%p", &staticValue1);
}
- (void)staticTestB
{
static int i = 0;
i++;
NSLog(@"staticTestB------------%d", i);
}
- (void)staticTestC
{
int i = 0;
i++;
NSLog(@"staticTestC------------%d", i);
}
@end
打印结果:
2017-12-08 17:25:51.862511+0800 Test[28720:12325782] staticTestA------------0x10f123148
2017-12-08 17:25:51.862617+0800 Test[28720:12325782] staticTestA------------0x10f123148
2017-12-08 17:25:51.862712+0800 Test[28720:12325782] staticTestB------------1
2017-12-08 17:25:51.862785+0800 Test[28720:12325782] staticTestB------------2
2017-12-08 17:25:51.862865+0800 Test[28720:12325782] staticTestC------------1
2017-12-08 17:25:51.862947+0800 Test[28720:12325782] staticTestC------------1
结论:
1、通过staticTestA和staticTestB发现static修饰局部变量确实只初始化一次只有一份内存
2、通过staticTestB和staticTestC发现使用static修饰局部变量和不使用static修饰,也能验证上面的结论
3、static修饰全局变量的作用域,仅限当前文件的话,大家可以自己验证,写两个文件,全局变量都命名成一样的名称(类似上面的staticValue2),试试加上static和不加的区别便知