IMP 到底是什么
IMP 的定义可以再 objc.h 中找到
1 2
| typedef void (*IMP)(void ); typedef void (*IMP)(void);
|
其实就是参数为空,返回值为空的函数指针。
#1 IMP 能直接调用么
定义一个类:
1 2 3 4 5 6 7 8 9 10 11
| @interface TestClass : NSObject
@end
@implementation TestClass
- (id)test:(NSInteger)arg { return nil; }
@end
|
获取 IMP 并调用:
1 2 3 4 5 6
| int main(int argc, char * argv[]) { IMP testIMP = class_getMethodImplementation([TestClass class], @selector(test:)); testIMP();
return 1; }
|
#2 IMP 的返回值和参数怎么定?
不对劲吧,参数没有传。怎么判断一个方法的具体参数呢:
1
| Method testMethod = class_getInstanceMethod([TestClass class], @selector(test:));
|
而 Method 是:
1 2 3 4 5
| struct objc_method { SEL method_name OBJC2_UNAVAILABLE; char *method_types OBJC2_UNAVAILABLE; IMP method_imp OBJC2_UNAVAILABLE; }
|
从调试窗口看到的:

method_types是@24@0:8q16[4], 内容都是一个字符跟一个数字成对出现, 第一对表示返回值和参数长度(其中@表示返回值为id, 24表示参数长度为24字节),后面三对代表三个参数(@0表示参数是id而参数的偏移为0, :8表示参数是selector偏移为8,q16表示参数为long long偏移为16), 完整的type encoding参见参考.
也就意味着test:方法的IMP的类型应该是id (*IMP)(id, SEL, long long), 其中参数的第一个id是self, 第二个SEL是当前IMP对应的selector, 第三个long long就是test:的arg参数. 更详细的介绍见参考.