面试题答案
一键面试- self调用实例方法查找过程:
- 当
self
调用实例方法时,运行时系统会从self
所指向对象的类的方法列表开始查找。如果在该类的方法列表中没有找到对应的方法实现,就会沿着继承体系链向上查找,直到找到该方法的实现或者到达根类NSObject
。如果在根类NSObject
中也没有找到,就会触发unrecognized selector sent to instance
异常。 - 例如,有一个类
SubClass
继承自SuperClass
:
- 当
#import <Foundation/Foundation.h>
@interface SuperClass : NSObject
- (void)superMethod;
@end
@implementation SuperClass
- (void)superMethod {
NSLog(@"This is superMethod in SuperClass");
}
@end
@interface SubClass : SuperClass
@end
@implementation SubClass
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
SubClass *sub = [[SubClass alloc] init];
[sub superMethod];
}
return 0;
}
在这个例子中,SubClass
没有实现superMethod
,self
(即sub
)调用superMethod
时,先在SubClass
的方法列表中查找,没找到就到SuperClass
的方法列表中查找,找到了并执行。
2. super调用实例方法查找过程:
super
并不是一个对象,而是一个编译器指示符。当使用super
调用实例方法时,编译器会告诉运行时系统从当前类的父类的方法列表开始查找方法实现。同样,如果在父类的方法列表中没有找到,会继续沿着继承体系链向上查找,直到找到方法实现或者到达根类NSObject
。- 例如,修改上述代码如下:
#import <Foundation/Foundation.h>
@interface SuperClass : NSObject
- (void)superMethod;
@end
@implementation SuperClass
- (void)superMethod {
NSLog(@"This is superMethod in SuperClass");
}
@end
@interface SubClass : SuperClass
- (void)subMethod;
@end
@implementation SubClass
- (void)subMethod {
[super superMethod];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
SubClass *sub = [[SubClass alloc] init];
[sub subMethod];
}
return 0;
}
在SubClass
的subMethod
中使用super
调用superMethod
,编译器会指示运行时系统从SubClass
的父类SuperClass
的方法列表开始查找superMethod
的实现。