面试题答案
一键面试动态绑定和消息传递机制
- 动态绑定:在Objective-C中,动态绑定是指在运行时(而非编译时)才确定对象要调用的方法实现。这意味着编译器在编译代码时,并不确切知道对象实际会调用哪个方法,而是在运行时根据对象的实际类型来决定。
- 消息传递机制:Objective-C通过消息传递来调用方法。当向一个对象发送消息时,运行时系统会在该对象的类的方法列表中查找与消息对应的方法实现。如果在该类中未找到,会沿着继承体系向父类查找,直到找到对应的方法实现或到达根类(
NSObject
)。
对多态性实现的意义
多态性允许不同类的对象对相同的消息做出不同的响应。动态绑定和消息传递机制是实现多态性的基础。通过动态绑定,运行时系统能够根据对象的实际类型选择正确的方法实现,从而使不同类的对象在接收到相同消息时可以执行不同的操作。
代码示例
#import <Foundation/Foundation.h>
// 定义基类Animal
@interface Animal : NSObject
- (void)makeSound;
@end
@implementation Animal
- (void)makeSound {
NSLog(@"Animal makes a sound.");
}
@end
// 定义子类Dog,继承自Animal
@interface Dog : Animal
- (void)makeSound;
@end
@implementation Dog
- (void)makeSound {
NSLog(@"Dog barks.");
}
@end
// 定义子类Cat,继承自Animal
@interface Cat : Animal
- (void)makeSound;
@end
@implementation Cat
- (void)makeSound {
NSLog(@"Cat meows.");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建Animal类型的数组,包含Dog和Cat对象
Animal *animals[2];
animals[0] = [[Dog alloc] init];
animals[1] = [[Cat alloc] init];
// 遍历数组并向每个对象发送makeSound消息
for (int i = 0; i < 2; i++) {
[animals[i] makeSound];
}
}
return 0;
}
在上述代码中:
Animal
类定义了makeSound
方法。Dog
和Cat
类继承自Animal
类,并各自重写了makeSound
方法。- 在
main
函数中,创建了一个Animal
类型的数组,其中包含Dog
和Cat
对象。 - 当遍历数组并向每个对象发送
makeSound
消息时,运行时系统会根据对象的实际类型(Dog
或Cat
)动态绑定到对应的makeSound
方法实现,从而实现多态性。输出结果为:
Dog barks.
Cat meows.
这表明运行时系统根据对象的实际类型正确地选择了重写后的方法。