iOS裏面Objective-C(OC)方法的懶加載 俗稱在運行過程當中動態的添加方法。函數
一、先建立Person類 把#import "Pseron.h" 引入 ViewControllerui
#import "ViewController.h" #import "Pseron.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Pseron * p = [[Pseron alloc]init]; //懶加載 用到的時候在加載方法!! [p performSelector:@selector(eat)]; [p performSelector:@selector(eat:) withObject:@"板燒雞腿堡"]; }
二、這樣編譯時 是報錯的,由於這個方法是沒有實現的,如今咱們要去動態的添加方法:來到Pseron.hspa
#import "Pseron.h" #import <objc/message.h> @implementation Pseron //C語言的 //全部的C語言的函數裏面!都有這兩個隱式參數!只要調用,哥麼系統都會傳遞進來! //不帶參數的 void eat(id self, SEL _cmd){ NSLog(@"調用了%@對象的%@方法",self,NSStringFromSelector(_cmd)); } //帶參數的 void eat1(id self, SEL _cmd,id obj){ NSLog(@"哥麼今晚吃五個%@",obj); } //當這個類被調用了沒有實現的方法!就會來到這裏 +(BOOL)resolveInstanceMethod:(SEL)sel{ // NSLog(@"你沒有實現這個方法%@",NSStringFromSelector(sel)); if (sel == @selector(eat)) { //這裏報黃色警告的話,沒問題的,由於系統編譯的時候不知道用了runtime已經添加了這個方法 /* 1.cls: 類類型 2.name: 方法編號 3.imp: 方法實現,函數指針! 4.types:函數類型 C字符串(代碼) void === "v" 5.cmd+shift+0去看文檔 */ class_addMethod([Pseron class],sel, (IMP)eat, "v@:"); }else if(sel == @selector(eat:)){ class_addMethod([Pseron class], sel, (IMP)eat1, "v@:@"); } return [super resolveInstanceMethod:sel]; }