The Preprocessor
- 从语言上定制Objective-C,使其适应自己的编程风格或特定的编程应用
- 是编译过程的一部分,识别散布在程序中的特定语句
- “#”开头
#define
- 给符号名称指派程序常量(包括但不限于)
- a defined name is not a variable; 字母全部大写
- often placed toward the beginning of the program, after #import or #include, but not required; must be placed before it is referenced by the program.
- more than a constant value: expression, “;”(所以不要用“;”结尾), 逻辑运算符, …
- Careful:使用#define重新定义底层语言语法的行为不是好习惯(会让人费解)
- 在#define语句中可以使用其他#define(不分前后)定义的符号名称
- good use of #define often reduces the need for comments
- macro 宏——常用带一个或多个参数的定义;
- syntax——#define NAME(参数) (表达式(参数)); //参数和表达式都要用()括起来,确保完整替换
- 简化表达式的编写
- macro中也可以使用其他macro
#import
- collect all your definitions into a separate file; import it and you can use
- (in Xcode 5) “@import UIKit;” module (new feature)
- 条件编译 Conditional Compilation
- often used to create one program that can be compiled to run on different computer systems (for example, an iPhone versus an iPad)
- switch on or off various statements in the program
条件控制语句
- #ifdef,#endif,#else,#ifndef 语句
- 检查某name是否已预编译(判断机型,系统,是否是debug状态……)
- #ifndef 与#ifdef 功能相同,条件相反
- if,#elif 语句——更加通用的条件编译控制
- test whether a constant expression evaluates to nonzero.是就执行后面语句直到#else、#elif或#endif;否就直接跳过
- #if defined (name) 与 #ifdef name 等价
- 添加注释的新方法:“#if 0 …注释… #endif”
- #undef 语句——remove the definition of a particular name :“#undef name”