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"