您的位置:首页 > 移动开发 > IOS开发

iOS中的const,static,extern

2017-02-09 14:14 197 查看
               iOS中的const,static,extern



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

int const xyz=123;

2.对于static(静态)

用几个例子来说:
第一个例子

#import "StaticLearn.h"

@implementation StaticLearn

static 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] 1
2017-02-09 13:41:46.318 UIKitLearn[2919:115349] 2
2017-02-09 13:41:46.318 UIKitLearn[2919:115349] 3static修饰延长了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] 1
2017-02-09 13:49:10.108 UIKitLearn[3099:121367] 2
2017-02-09 13:49:10.109 UIKitLearn[3099:121367] 3
2017-02-09 13:49:10.109 UIKitLearn[3099:121367] 4
2017-02-09 13:49:10.109 UIKitLearn[3099:121367] 5
2017-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错误
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: