static作用:
(1)函数体内 static 变量的作用范围为该函数体,不同于 auto 变量,该变量的内存只被分配一次, 因此其值在下次调用时仍维持上次的值;(比如在cell的重用标志中用static来修饰字符串,原因是:使用static会将字符串放到静态区,程序运行过程中,只会初始化一次,作为cell的重用标识一般使用static修饰,确保能是cell进行重用)
(2)在模块内的 static 全局变量可以被模块内所用函数访问,但不能被模块外其它函数访问;
(3)在模块内的 static 函数只可被这一模块内的其它函数调用,这个函数的使用范围被限制在声明 它的模块内;(但是在类之外是没有办法来访问的,相当于static变量都是私有的。)
(4)在类中的 static 成员变量属于整个类所拥有,对类的所有对象只有一份拷贝;
(5)在类中的 static 成员函数属于整个类所拥有,这个函数不接收 this 指针,因而只能访问类的static 成员变量。
如果.m文件和方法体里面定义了同名的static 变量,那么方法体里面的实例变量和全局的static变量不会冲突,在方法体内部访问的static变量和全局的static变量是不同的。
例如:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
static int count = 4;
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 100)];
[button setTitle:@"打印按钮" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
static int count = 5;
NSLog(@"%d",count);
}
-(void)buttonClicked:(UIButton *)button {
NSLog(@"%d",count);
}
运行后结果为:
2016-06-07 11:06:40.378 ExternDemo[1137:31475] 5
点击了打印按钮后结果为:
2016-06-07 11:06:43.860 ExternDemo[1137:31475] 4
说明- (void)viewDidLoad方法内部,访问的是方法体内部定义的count变量。在-(void)buttonClicked:(UIButton *)button方法体里面,访问的全局定义的count变量。