面试题答案
一键面试Selector
Selector是一个指向方法的selector(选择器)的指针,它本质上是一个唯一标识方法的字符串。在Objective-C中,每个方法都有一个与之对应的selector,它在编译期就被确定下来,并且在运行时保持不变。它的作用是在运行时查找和定位方法。例如,对于- (void)sayHello
这个方法,它对应的selector就是@selector(sayHello)
。
IMP
IMP是一个函数指针,它指向方法实现的具体代码。也就是说,当调用一个方法时,最终是通过这个函数指针来找到并执行实际的代码。不同类中相同名称的方法可能有不同的IMP,因为它们的实现可能不同。
关系
Selector和IMP通过类的方法列表关联起来。当向一个对象发送消息时,运行时系统首先根据消息中的selector在该对象所属类的方法列表中查找对应的IMP。找到IMP后,就通过这个函数指针来执行方法的具体实现。
通过运行时获取Selector和IMP示例
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)sayHello;
@end
@implementation Person
- (void)sayHello {
NSLog(@"Hello!");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc] init];
// 获取Selector
SEL selector = @selector(sayHello);
// 获取IMP
Method method = class_getInstanceMethod([person class], selector);
IMP imp = method_getImplementation(method);
// 打印Selector和IMP
NSLog(@"Selector: %@", NSStringFromSelector(selector));
NSLog(@"IMP: %p", imp);
}
return 0;
}
在上述代码中,通过@selector
获取了sayHello
方法的selector,然后使用class_getInstanceMethod
根据类和selector获取到Method
结构体,再通过method_getImplementation
从Method
结构体中获取到对应的IMP。