import "ViewController.h"
import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc]init];
// performSelector 動(dòng)態(tài)添加方法
// [p performSelector:@selector(eat)];
[p performSelector:@selector(eat:) withObject:@111];
}
@end
import "Person.h"
import <objc/message.h>
@implementation Person
// 定義一個(gè)函數(shù) 這個(gè)就是動(dòng)態(tài)添加的方法
void aaa(id self, SEL _cmd ,id param){
NSLog(@"這個(gè)就是eat方法%@",param);
}
void dynamicMethodIMP(id self, SEL _cmd) {
// 默認(rèn)的方法有2個(gè)參數(shù) self :方法調(diào)用者
// ——cmd 調(diào)用參數(shù)的編號(hào) 這兩個(gè)參數(shù)是隱新參數(shù)
}
// 動(dòng)態(tài)天假方法首先要實(shí)現(xiàn)reslveinstancemethod
// resloveInstanceMethod 調(diào)用 :當(dāng)一個(gè)方法沒(méi)有實(shí)現(xiàn)但是又吊用了這個(gè)方法就會(huì)調(diào)用 resolveInstanceMethod
// resloveInstanceMethod 作用:就知道了哪些方法沒(méi)有實(shí)現(xiàn)就可以動(dòng)態(tài)的添加方法
// sel:沒(méi)有實(shí)現(xiàn)的方法
+(BOOL)resolveInstanceMethod:(SEL)sel{
NSLog(@"%@",NSStringFromSelector(sel));
if(sel == @selector(eat:)){
// 參數(shù): clas 給哪個(gè)類添加方法 sel :添加方法的編號(hào) imp 方法的實(shí)現(xiàn)(函數(shù)的入口捷枯,函數(shù)的指針 函數(shù)名) types 方法的類型
這里的參數(shù)v代表void 请梢,@代表 對(duì)象 :代表sel @代表 Id
class_addMethod(self, sel, (IMP)aaa, "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}