rutime動態添加方法

import "ViewController.h"

import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    Person *p = [[Person alloc]init];
    // performSelector 動態添加方法
    // [p performSelector:@selector(eat)];
    [p performSelector:@selector(eat:) withObject:@111];
    }

@end

import "Person.h"

import <objc/message.h>

@implementation Person

// 定義一個函數 這個就是動態添加的方法
void aaa(id self, SEL _cmd ,id param){

NSLog(@"這個就是eat方法%@",param);

}

void dynamicMethodIMP(id self, SEL _cmd) {
// 默認的方法有2個參數 self :方法調用者
// ——cmd 調用參數的編號 這兩個參數是隱新參數
}
// 動態天假方法首先要實現reslveinstancemethod
// resloveInstanceMethod 調用 :當一個方法沒有實現但是又吊用了這個方法就會調用 resolveInstanceMethod
// resloveInstanceMethod 作用:就知道了哪些方法沒有實現就可以動態的添加方法
// sel:沒有實現的方法

+(BOOL)resolveInstanceMethod:(SEL)sel{

NSLog(@"%@",NSStringFromSelector(sel));
if(sel == @selector(eat:)){
  // 參數: clas  給哪個類添加方法  sel :添加方法的編號 imp 方法的實現(函數的入口,函數的指針 函數名) types 方法的類型

這里的參數v代表void ,@代表 對象 :代表sel @代表 Id
class_addMethod(self, sel, (IMP)aaa, "v@:@");
return YES;
}

return [super resolveInstanceMethod:sel];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容