BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)参数:第一个为将要被运行时修改的类,第二个是加入的选择器,第三个为IMP指针,第四个为函数的参数类型。其中第三,第四参数需要解释一下,IMP 其实类似一个函数指针,可见 runtime 实际上是连接开发者与 object-c 底层的桥梁,开发者面对的是OOD,对象,选择器,方法,而object-c 底层是由 c 来实现的,c只有函数,所以 IMP 其实就是根据 selector 来获取一个底层对应的函数指针。types 是告诉运行时,该函数的参数,和返回值的类型,可参考官方文档 Table 6-1 Objective-C type encodings。types的格式为 "返回值类型 参数类型1:参数类型2:参数类型3"。举个例子:给 GridMovingController 类,添加一个方法, - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section。代码如下:
class_addMethod([GridMovingController class], @selector(tableView:viewForHeaderInSection:), [self methodForSelector:@selector(tableView:viewForHeaderInSection:)], "@@:i"); //types为"@@:i",表示返回值为对象,第一个参数为对象,第二个参数为int。如果返回值为void types 为"v@:i"