iOS runtime動態新增方法

2022-08-31 03:15:13 字數 1089 閱讀 9143

1. 為什麼要給乙個類動態新增方法?

如果乙個類有很多的方法, 當我們載入這個類的時候會比較消耗記憶體資源, 需要給每個方法生成對映表,  我們可以動態給這個類新增方法

2. 乙個類動態新增方法的好處?

1. 減少載入類是記憶體的消耗

2. 可以呼叫乙個未實現的方法和去除報錯

3. 主要使用的api

1. + (bool)resolveinstancemethod:(sel)sel; // 被呼叫的方法實現部分沒有找到,而訊息**機制啟動之前的這個中間時刻。

2. class_addmethod(<#class  _nullable __unsafe_unretained cls#>, <#sel  _nonnull name#>, <#imp  _nonnull imp#>, <#const char * _nullable types#>)               // 為乙個類動態新增方法

<#class  _nullable __unsafe_unretained cls#>: 為哪乙個類新增方法  

<#sel  _nonnull name#>: 方法的註冊名稱 

<#imp  _nonnull imp#>: 方法的指標, 可以通過class_getmethodimplementation(class cls, sel name)來獲取

<#const char * _nullable types#>: 方法返回值型別, 入參; 比如: "v@:@", v: 返回的引數型別, @:代表自己, @乙個引數

4. 呼叫performselector: 是執行時系統負責去找方法的,在編譯時候不做任何校驗;如果直接呼叫編譯是會自動校驗。

5. 例項:

//動態新增乙個方法

person *p = [[person alloc]init];

class_addmethod([person class], @selector(printperson), class_getmethodimplementation([viewcontroller class], @selector(find)), "v@:");

[p performselector:@selector(printperson)];

iOS runtime 動態新增屬性

qq群 807236138 群稱 ios 技術交流學習群 1.runtime 動態新增屬性 什麼時候需要動態新增屬性 2.開發場景 給系統的類新增屬性的時候,可以使用runtime動態新增屬性方法 3.本質 動態新增屬性,就是讓某個屬性與物件產生關聯。runtime一般都是針對系統的類 4.在分類中...

iOS Runtime4 動態新增屬性

為uiimage的類目新增屬性imageurl使用 示例 uiimage image.h inte ce uiimage image property nonatomic,copy nsstring imageurl 動態新增屬性 end uiimage image.m implementation...

IOS runtime動態執行時一

對執行時不太了解,今天小夥伴橄欖油陳高給發了個鏈結 看了一部分先存著以後慢慢品 今天一句一句的讀了下 慢慢有了點感覺,把主要的截圖貼在這以後好多看幾遍 typedef struct objc class class struct objc class class isa 指向metaclass,也就...