iOS中的const,static,extern

来源:互联网 发布:金税发票数据导出软件 编辑:程序博客网 时间:2024/05/31 13:16

               iOS中的const,static,extern


1.对于const,没啥说的,如下,修饰了,就算只读了

int const xyz=123;


2.对于static(静态

用几个例子来说:

第一个例子

#import "StaticLearn.h"@implementation StaticLearnstatic int lizi = 1;+(int)learn{    return lizi++;}-(int)learn1{    return lizi++;}@end
类StaticLearn里面有一个static变量lizi,初始化值为1,类有一个类方法和一个对象方法,我们使用一下看看

    NSLog(@"%d",[StaticLearn learn]);    NSLog(@"%d",[StaticLearn learn]);    NSLog(@"%d",[StaticLearn learn]);
输出结果为:

2017-02-09 13:41:46.317 UIKitLearn[2919:115349] 12017-02-09 13:41:46.318 UIKitLearn[2919:115349] 22017-02-09 13:41:46.318 UIKitLearn[2919:115349] 3
static修饰延长了lizi的生命周期(记得以前看书,好像static修饰会改变变量存储模式,好像会从栈移到堆,这个考究一下再回来确定)


第二个例子

我们用对象方法尝试:

    StaticLearn *sl = [[StaticLearn alloc]init];    NSLog(@"%d",[sl learn1]);    NSLog(@"%d",[sl learn1]);    NSLog(@"%d",[sl learn1]);    sl = nil;    sl = [[StaticLearn alloc]init];    NSLog(@"%d",[sl learn1]);    NSLog(@"%d",[sl learn1]);    NSLog(@"%d",[sl learn1]);
我们生成对象,输出结果为:

2017-02-09 13:49:10.108 UIKitLearn[3099:121367] 12017-02-09 13:49:10.108 UIKitLearn[3099:121367] 22017-02-09 13:49:10.109 UIKitLearn[3099:121367] 32017-02-09 13:49:10.109 UIKitLearn[3099:121367] 42017-02-09 13:49:10.109 UIKitLearn[3099:121367] 52017-02-09 13:49:10.109 UIKitLearn[3099:121367] 6
写了这个例子让我对static修饰的变量存储位置产生疑问,懂的同学评论给我


第三个例子

-(int)learn2{    static int i = 1;    return i;}-(int)learn3{    return i;}
这样的写法是错误的,也就是static不能改变i的作用域


3.对于extern

按字面理解,外部外来的,那么extern修饰的变量应该是来自外部的,即是其他文件里声明的变量

这里说下我的使用,具体为什么这样写。。。我现在还没摸清

有两个类A和B

第一种

在A.m文件里声明

NSString *haha = @"hello";

在B.h或者B.m文件中

extern NSString *haha;
在B.m文件中 

NSLog(@"%@",haha);
这样输出的即为‘hello’,在B中改变haha的值,A中的值也会同样变化

但我不太明白,为什么在A.h文件中不能声明,会出现linker错误








3 0
原创粉丝点击