静态变量-static关键词

一、静态变量static用法

需声明在@implementaion中,如果声明在@interface或@protocol中:

@property (nonatomic, strong) static NSString *s2;

报错:Type name does not allow storage class to be specified;

二、静态变量static的注意点:

1、在编译期,会对static修饰的变量进行初始化赋值。也就是说这个变量值要么为nil,要么在编译期就可以确定其值;

2、类变量,只有一份,且类的所有对象均能访问此变量;

3、方法体中,static变量只能在对应的方法体里面访问,但是变量确是类变量;

4、类的私有变量,声明在implementation中、方法外,只能由implementation中的方法访问。

第1注意点体现代码:

int main(int argc, const char * argv[]) {
    void test();
    test();
    test();
    return 0;
}

void test(){
    static int count = 0;
    count++;
    NSLog(@"count = %i", count);
}

输出结果:count = 1;

     count = 2;

posted on 2015-12-22 14:36  Beche  阅读(1042)  评论(0编辑  收藏  举报

导航