一、runtime簡介
1.runtime 簡稱運行時,OC就是運行時機制,也就是在運行時候的一些機制,其中最主要的是消息機制
2.對於C語言,函數在編譯的時候會決定調用哪個函數
3.對於OC函數,屬於動態調用過程,在編譯的時候並不能決定真正調用哪個函數,只有在真正運行的時候纔會根據函數的名稱找到對應的函數
實踐證明:在編譯階段,OC可以調用任何函數,即使這個函數並未實現,只要聲明過就不會報錯
在編譯階段,C語言調用未實現的函數就會報錯
二、runtime的作用
1.發送消息
~方法調用的本質,就是讓對象發送消息
~objc_msgSend只有對象才能發送消息,因此以objc開頭
2.使用運行時消息機制的步驟:
~先導入 #import<objc/message.h>
四、runtime動態添加方法
添加不帶參數的方法:
@implementation Person
//動態添加方法,首先實現這個resolveInstanceMethod
//resolveInstanceMethod調用時間:調用了一個沒有實現的方法,這時會調用resolveInstanceMethod方法
//resolveInstanceMethod方法作用:
//sel:爲沒有實現的方法
void addrun()
{
NSLog(@"動態添加了一個方法");
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel==@selector(run)) {
/*
cls:給哪個類添加方法
SEL:添加方法的方法編號是什麼
IMP:方法實現,函數入口,函數名
types:方法類型
*/
class_addMethod(self, sel, (IMP)addrun, "v@:");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
Person * person = [[Person alloc]init];
[person performSelector:@selector(run) withObject:nil];
添加一個帶參數的方法
@implementation Person
//動態添加方法,首先實現這個resolveInstanceMethod
//resolveInstanceMethod調用時間:調用了一個沒有實現的方法,這時會調用resolveInstanceMethod方法
//resolveInstanceMethod方法作用:
//sel:爲沒有實現的方法
void addrun(id self,SEL _cmd,id param)
{
NSLog(@"動態添加了一個方法---------%@",param);
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel==@selector(run)) {
/*
cls:給哪個類添加方法
SEL:添加方法的方法編號是什麼
IMP:方法實現,函數入口,函數名
types:方法類型
*/
class_addMethod(self, sel, (IMP)addrun, "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person * person = [[Person alloc]init];
[person performSelector:@selector(run) withObject:@123];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
class_addMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>, <#IMP imp#>, <#const char *types#>)
傳遞的各個參數說明 cls:給哪個類添加方法
SEL:添加方法的方法編號是什麼
IMP:方法實現,函數入口,函數名
types:方法類型 方法類型確定需要到
五、動態添加屬性