iOS const static extern
2019-08-15 本文已影响0人
相约星期二GM
前言
本篇主要介绍在开发中怎么使用const,static,extern3个关键字
一、Const
简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们使用const常量。
1.const用来修饰右边的基本变量或指针变量
2.被修饰的变量只读,不能被修改
1.1 基本数据类型
int const a = 1;
const int b = 1; // 等价
a = 10; // 错误
b = 10; // 错误
1.2 指针类型
1.2.1 指针符号左侧
int a = 1;
int b = 2;
int const *p = &a;
p = &b;
*p = 10; // 错误
1.2.2 指针符号右侧
int a = 1;
int b = 2;
int *const p = &a;
*p = 10;
p = &b; // 错误
1.2.3 指针符号两侧
int a = 1;
int b = 2;
int const * const p = &a;
*p = 10; // 错误
p = &b; // 错误
1.2.4 练习
int const *p // *p只读; p变量
int * const p // p只读; *p变量
const int * const p // p和*p都是只读
int const * const p // p和*p都是只读
二、Static
2.1 修饰局部变量
static让局部变量只初始化一次,生命周期已经跟全局变量类似了,只是作用域不变。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 声明一个局部变量i
static int i = 0;
// 每次点击view来到这个方法时让i自增
i ++;
//打印结果 1,2,3,4,5....
NSLog(@"i=%d",i);
}
2.2 修饰全局变量
iOS中在一个文件声明的全局变量,但又不想让其他文件访问,这时就可以用static修饰它了,单例中全局变量基本上都会用static修饰。
@implementation UserTool
// static修饰全局变量,让外界文件无法访问
static UserTool *_sharedManager = nil;
+ (LoginTool *)sharedManager {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedManager = [[self alloc] init];
});
return _sharedManager;
}
三、 extern
extern主要是用来引用全局变量,它的原理就是先在本文件中查找,本文件中查找不到再到其他文件中查找。
常把extern和const联合使用在项目中创建一个文件,这个文件文件中包含整个项目中都能访问的全局常量。
extern NSString * homeName;
四、static和const联合使用
// static修饰后此全局变量只能本文件访问
static NSString *const name= @"名字";
五、extern和const联合使用
// .h文件声明
extern NSString * const homeName;
// .m文件定义
NSString * const homeName = @"首页";