【iOS】const, static, extern使用详解

const与宏:

const : 之前常用的字符串常量,一般是抽成宏,Apple不推荐使用宏,推荐使用const常量。
- 宏是预编译时处理(编译之前),const则是编译阶段;
- 宏只是替换,不做检查,不报编译错误,const会编译检查,会报编译错误;
- 宏能定义一些函数、方法, const则不能;
- 使用大量宏,容易造成编译时间久,每次都需要重新替换;

!

结论 :* 宏定义的是常量,放在常量区,只会有一份内存 *

const 修饰变量是只读的:

const int a = 10;
a = 20; //错误,不允许修改a的值

const用法:

//只读变量,写法是一致的;
const int a = 10;
int const a = 10;

//const 修饰右边的*point1,*point1常量,point1变量
const int *point1;
int const *point1;

// const修饰指针变量point1
int * const point1; // *point1:变量 point1:常量

// 第一个const修饰*point1 第二个const修饰 point1
// 两种方式一样
const int * const point1; // *point1:常量 point1:常量
int const * const point1;  // *point1:常量 point1:常量

static & extern:

!

运行结果

static 和const一起使用:声明一个只读静态变量

        static NSString * const key = @"WTF(Wen, Thu, Fri)";
        static NSString const *key1 = @"WTF(Wen, Thu, Fri)";

        NSLog(@"%@", key);
        //key = @"hah"; //key为只读

        NSLog(@"key1 %@", key1);
        key1 = @"FTW";
        NSLog(@"key1 %@", key1);
        //修饰的是*key1只读,key还是可以改变

extern & const:

使用场景:多文件中常用同一个字符串变量,可以用extern+const联合声明。
- static + const:每个文件都需定义;
- extern + const:只需定义一份全局变量,多文件共享

.h:
extern NSString * const key = @"key";

.m:
NSString *const key = @"key"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值