iOS之《Effective Objective-C 2.0》读书笔记(4)

第四条:多用类型常量,少用#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)宏定义常量可能会被修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值