Chapter 10 More on Variables and Data Types
主要内容:
- variable scope
- initialization methods for objects
- data types in more detail ——enum枚举
初始化
- initialization methods:初始化+赋初值
- override init方法的“模板”syntax :
- (instancetype) init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (关键字)特殊类型 instancetype:the return type from the init method will be the same class as the type of object it is initializing (that is, the receiver of the init message).
- self = [super init]; //首先调用父类的初始化方法,确保所有子类继承的实例变量能够正确初始化;初始化方法可以改变对象在内存中的地址,所以要把返回值赋给对象
- if (self) //self非空,表示父类初始化方法运行正常,可以进行下一步操作(子类特有的初始化方法)
多个初始化方法的情形:应该指定一个初始化方法(通常为参数最多的一个,一般名为initWith……)作为其余初始化方法的参考(即其他方法使用此指定方法),对子类override init方法也很重要。
当程序运行时,初始化消息会发送给所有的类(继承序列上的):父类先于子类接收,每个类只接收一次,所有类最先接收到的消息必定是初始化消息。
变量作用域
module 模块 :any number of method or function definitions contained within a single source file
use an underscore(_) as the leading character for an instance variable
使用@synthesize 属性名 = 对应实例变量名(_属性名)→ 实例变量也能获得accessor methods,但是使用实例变量是依然要用 实例变量名 或 self.属性名(better)
- private → 子类只有通过继承的accessor方法才能访问
- 在@interface中声明的@property,会在@implementation部分中自动添加对应实例变量(加_)而不需要再写@synthesize语句
- 加入@synthesize语句则可以直接使用变量(不加_,也不用self.)
全局变量 Global variables:通常首字母使用小写g,以向读者表明这是全局变量
外部external global variables:用关键字extern声明 → extern int gGlobalVar;
- 其他module可以通过此种声明形式来访问变量gGlobalVar(先声明后访问)
- 必须在source file中定义global variables(不能在extern声明语句中);此文件使用此global variable不用extern声明
- extern声明可以(方法内/外)有多次,但是定义只能有一次
- 较好的使用方式:
- 如果有多个方法需要访问此global variable,在文件的前面使用一次extern声明(简化code)
- 如果只有一个或少量方法需要访问,在每个方法内单独使用extern声明(结构清晰)
静态变量 Static variables:用关键字static定义 → static int gGlobalVar = 0;
- global, but not external ——作用域限定在定义的module内
- 可以供类方法使用的变量(类方法不能使用实例变量)
- a simple example is a class allocator method that you want to keep track of the number of objects it has allocated.
- 不要override alloc方法(与内存操作有关),而是在其基础上扩展功能
枚举类型
定义枚举类型的syntax:enum 名称 {Identifier 1, Identifier 2, Identifier 3, …};
使用:
- 声明一个枚举类型的变量:“enum 枚举类型名 变量1, 变量2, …;”
- 枚举类型变量可赋值,可直接用于判断
- 理论上,枚举类型变量能接收的赋值仅限于枚举类型限定的Identifier
直接定义枚举类型变量:enum { identifiers} 变量名;
编译器处理:
- Identifier 1如果没有赋值则默认为整数0,赋值即为对应值
- 后面的Identifier,如果没有赋值,则自动设为前一个Identifier的值+1;赋值则为对应值
- Identifiers之间可以共用一个值
枚举类型变量赋值给其他变量:对应Identifier所具有的int型常数
int型变量变量可以赋值给枚举类型变量:强制类型转换“(enum 枚举类型变量名)”
定义位置决定其作用域:在block内则限于block内使用;在文件开头则可在整个文件内使用
typedef语句——提高变量定义的可读性
- write the statement as if a variable of the desired type were being declared
- 在变量名的地方,用新的类型名替换之
- in front of everything, place the keyword typedef
typedef enum {identifiers} newName; //用newName直接声明变量
数据类型转换
简要关系
- long double > double > float
- _BOOL, char, short int, bitfield, enum → int
- long long int > long int > int
强制类型转换符
位运算符 Bit Operators