MST

星途 面试题库

面试题:Objective-C中self与super在方法调用上的区别

在Objective-C中,描述self与super在调用实例方法时,其查找方法实现的过程有何不同,并举例说明。
38.1万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 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没有实现superMethodself(即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;
}

SubClasssubMethod中使用super调用superMethod,编译器会指示运行时系统从SubClass的父类SuperClass的方法列表开始查找superMethod的实现。