BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
作用:这个方法的作用是,给类添加一个新的方法和该方法的具体实现
BOOL: 返回值,yes-------方法添加成功 no--------方法添加失败
Class cls: 将要给添加方法的类,传的类型 [类名 class]
SEL name: 将要添加的方法名,传的类型 @selector(方法名)
IMP imp:实现这个方法的函数 ,传的类型 1,C语言写法:(IMP)方法名 2,OC的写法:class_getMethodImplementation(self,@selector(方法名:))
{
C语言举例:
void startEngine(id self, SEL _cmd, NSString *brand) { NSLog(@"my %@ car starts the engine", brand); } @implementation Car (myCar) + (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(drive)) { class_addMethod([self class], sel, (IMP)startEngine, "v@:@"); return YES; } return [super resolveInstanceMethod:sel]; } @end
OC写法举例:
@implementation Car (myCar) + (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(drive)) { class_addMethod([self class], sel, class_getMethodImplementation(self, @selector(startEngine:)), "s@:@"); return YES; } return [super resolveInstanceMethod:sel]; } - (void)startEngine:(NSString *)brand { NSLog(@"my %@ car starts the engine", brand); } @end
}
const char *types:表示我们要添加的方法的返回值和参数
"v@:@":v:是添加方法无返回值 @表示是id(也就是要添加的类) :表示添加的方法类型 @表示:参数类型
const char *types含义表: