id数据类型属于一种通用的对象类型,可用于存储任何类的对象
可以存储不同类型的对象,也有其优势在
id dataValue;
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
dataValue = f1;
[dataValue print];
dataValue = c1;
[dataValue print];
id dataValue,没有星号哦~
Fraction和Complex都定义了print方法,由于dataValue先指定的Fraction,所以,dataValue的print是由Fraction定义的。后面的才是由Complex定义的print
例如:考虑可用来绘制屏幕图形的draw方法,将特定对象存入currentObject的id变量中,仅仅发送draw消息就可以绘制了
[currentObject draw];
甚至可以先测试它,确保存储在currentObject中的对象的确相应draw方法。
编译时和运行时检查:
由于程序在编译的时候无法确定id中的对象类型,所以,测试会推迟到运行的时候进行
Fraction *f1 = [[Fraction alloc] init];
[f1 setReal:10.0 andImaginary:2.5];
此时,由于Fraction类并不包含setReal:andImaginary:方法,所以会生成警告
id dataValue = [[Fraction alloc] init];
[dataValue setReal: 10.0 andImaginary: 2.5];
此时,代码在编译时,编译器不会产生警告。程序会在运行时,出现出错信息。