動態新增方法,新增協議

2021-07-10 23:37:47 字數 1602 閱讀 7180

void newmethod(id self,sel _cmd,nsstring *str)

/**cls:被新增方法的類

name:可以理解為方法名,貌似隨便起名,比如我們這裡叫newmethod2222

imp:實現這個方法的函式

type: 具體還太熟悉,type應該是被削弱了,返回值不准也可以正常執行,

v:表示無返回值,

@:引數id(self) 可以不寫

::sel(_cmd) 可以不寫

@:id(str) 需要

*//**tpye的型別,

code meaning

r const 常量

n in

n inout

o out

o bycopy

r byref

v oneway 無返回值的void

*/class_addmethod([test class],nsselectorfromstring(@"newmethod2"), (imp)newmethod, "v@:@");//type還可以寫成"v@","i@:@"

// test method

test *instance = [[test alloc] init];

[instance performselector:nsselectorfromstring(@"newmethod2") withobject:@"hello"];//這時xcode會報警告,

//可以用afterdelay消除警告,

[instance performselector:nsselectorfromstring(@"newmethod2") withobject:@"hello" afterdelay:0.f];//但是如果需要用到返回值時,即:

//int a = [instance performselector:nsselectorfromstring(@"newmethod2") withobject:@"hello" afterdelay:0.f];//這時會報錯,可以用函式指標解決

sel selector = nsselectorfromstring(@"sayhello2");

imp imp = [test methodforselector:selector];

int (*func)(id, sel, nsstring *) = (void *)imp;//帶引數,nsstring* 是帶的引數,可以帶多個參

int a = func(test, selector, @"hello");

//或者還可以用runtime的msg

//int a = ((int(*)(id,sel,nsstring *))objc_msgsend)(test,nsselectorfromstring(@"sayhello2"),@"hello");

nslog(@"%zi",a);

/************新增協議**********/

class_addprotocol([testobject class], objc_getprotocol("nscoding"));

runtime 動態新增方法

動態新增方法 動態新增就運用到懶載入 開發場景 如果乙個類方法很多,載入類到記憶體的時候也比較耗費資源,需要給每個方法生成乙個對映表 這個詞我也不懂 可以使用動態給某個類新增方法。person p person alloc init perform selector 即為動態新增方法 p perfo...

Runtime(動態新增方法)

a問 有沒有使用過performselector,什麼時候使用?動態新增方法的時候使用過?怎麼動態新增方法?用runtime?為什麼要動態新增方法?b runtime 動態新增方法 oc都是懶載入機制,只要乙個方法實現了,就會馬上新增到方法列表中.qq,微博,直播等等應用,都有會員機制 任何方法預設...

iOS runtime動態新增方法

1.為什麼要給乙個類動態新增方法?如果乙個類有很多的方法,當我們載入這個類的時候會比較消耗記憶體資源,需要給每個方法生成對映表,我們可以動態給這個類新增方法 2.乙個類動態新增方法的好處?1.減少載入類是記憶體的消耗 2.可以呼叫乙個未實現的方法和去除報錯 3.主要使用的api 1.bool res...