第四条:多用类型常量,少用#define预处理指令
1.宏定义的使用(#define)
(1)预处理命令不是一个常量,而是变量
#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
(2)定义代码
#define isIOS7 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]==7)
#define kNotificationCenter [NSNotificationCenter defaultCenter]
(3)定义系统信息
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
2.类型常量的使用:(const)
(1)const:修饰符定义的常量是不可变的,它仅仅用来修饰右边的常量
1.需要定义一个动画时间的常量
static const NSTimeInterval kAnimateDuration = 0.3;
2.定义一个字符串:第三种写法定义的kUserName不可修改
NSString const * kUserName = @"StrongX";
const NSString * kUserName = @"StrongX";
NSString * const kUserName = @"StrongX";
(2)extern:修饰全局变量
//1>如果是多个文件共享的常量,在.h文件声明一个字符串,在.m中实现就可以了
Config.h
extern NSString * const nameKey
Config.m
NSString * const nameKey = @"name";
//2>单个文件
extern NSString * const nameKey = @"name";
(3)static:修饰局部变量
static NSString * const key = @"name";
3.#define与const区别:
(1)编译时刻不同:宏属于预编译 ,const属于编译时刻
(2)宏能定义代码,const不能
(3)宏不会检查错误,const会检查错误
(4)多个宏对于编译会相对时间较长,影响开发效率,调试过慢,const只会编译一次,缩短编译时间。
(5)const定义是带有类型信息的
(6)宏定义常量可能会被修改