(1)id在动态类型的应用
在Objective-C Runtime Reference中,对id是这么定义和声明的:
id
A pointer to an instance of a class.
Declaration
typedef struct objc_object *id;
从定义来看,id是一个指向某个类的实例的指针。从声明来看,id是一个类型的别名,这个类型是“struct objc_object *”,也就是代表了指向一个objc_object结构体的指针。
id是一种通用的对象类型,可以用来存储任何类型的对象。也可以理解为“万能指针”。下面是《Programming in Objective-C》对id的作用的描述:
“That is, id can be used for storing objects that belong to any class. That real power of this data type is exploited when it’s used this way to store different types of objects in a variable during the execution of a program”
也就是,id可用于动态类型(dynamic typing)和动态绑定(dynamic binding)。例子如下:
// Animal.h
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)eat;
@end
// Animal.m
#import "Animal.h"
@implementation Animal
-(void)eat{
NSLog(@"animal eat!");
}
@end
// Person.h
#import "Animal.h"
@interface Person : Animal // Person类继承了Animal类
@end
// Person.m
#import "Person.h"
-(void)eat{
NSLog(@"person eat!"); // 重写了Animal类中的eat方法
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
id anInstance; //此时 anInstance 对象为 id类型
Animal *animal = [[Animal alloc] init];
Person *person = [[Person alloc] init];
anInstance = animal; //此时 anInstance 对象存储了 Ani