runtime簡介
因?yàn)镺bjc是一門動態(tài)語言,所以它總是想辦法把一些決定工作從編譯連接推遲到運(yùn)行時。也就是說只有編譯器是不夠的,還需要一個運(yùn)行時系統(tǒng)(runtime system) 來執(zhí)行編譯后的代碼。這就是 Objective-C Runtime系統(tǒng)存在的意義,它是整個Objc運(yùn)行框架的一塊基石。RunTime簡稱運(yùn)行時。OC就是運(yùn)行時機(jī)制,其中最主要的是消息機(jī)制。對于C語言,函數(shù)的調(diào)用在編譯的時候會決定調(diào)用哪個函數(shù)。對于OC的函數(shù),屬于動態(tài)調(diào)用過程,在編譯的時候并不能決定真正調(diào)用哪個函數(shù),只有在真正運(yùn)行的時候才會根據(jù)函數(shù)的名稱找到對應(yīng)的函數(shù)來調(diào)用。Runtime基本是用C和匯編寫的,可見蘋果為了動態(tài)系統(tǒng)的高效而作出的努力。你可以在這里下到蘋果維護(hù)的開源代碼。蘋果和GNU各自維護(hù)一個開源的runtime版本,這兩個版本之間都在努力的保持一致。
Runtime相關(guān)的頭文件
ios的sdk中 usr/include/objc文件夾下面有這樣幾個文件
都是和運(yùn)行時相關(guān)的頭文件,其中主要使用的函數(shù)定義在message.h和runtime.h這兩個文件中。 在message.h中主要包含了一些向?qū)ο蟀l(fā)送消息的函數(shù),這是OC對象方法調(diào)用的底層實(shí)現(xiàn)。
使用時,需要導(dǎo)入文件,導(dǎo)入如:
#import<object/message.g>
#import<object/runtime.h>
runtime.h是運(yùn)行時最重要的文件,其中包含了對運(yùn)行時進(jìn)行操作的方法。 主要包括:
操作對象的類型的定義
///An opaque type that represents a method in a class definition. 一個類型,代表著類定義中的一個方法
typedefstructobjc_method *Method;
///An opaque type that represents an instance variable.代表實(shí)例(對象)的變量typedefstructobjc_ivar *Ivar;
///An opaque type that represents a category.代表一個分類
typedefstructobjc_category *Category;
///An opaque type that represents an Objective-C declared property.代表OC聲明的屬性typedefstructobjc_property *objc_property_t;
//Class代表一個類,它在objc.h中這樣定義的? typedef struct objc_class;
*Class;structobjc_class {
Class isa? OBJC_ISA_AVAILABILITY;#if!__OBJC2__Class super_class? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? OBJC2_UNAVAILABLE;constchar*name? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;longversion? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;longinfo? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;longinstance_size? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;structobjc_ivar_list *ivars? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;structobjc_method_list **methodLists? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;structobjc_cache *cache? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;structobjc_protocol_list *protocols? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;#endif} OBJC2_UNAVAILABLE;
這些類型的定義,對一個類進(jìn)行了完全的分解,將類定義或者對象的每一個部分都抽象為一個類型type,對操作一個類屬性和方法非常方便。OBJC2_UNAVAILABLE標(biāo)記的屬性是Ojective-C 2.0不支持的,但實(shí)際上可以用響應(yīng)的函數(shù)獲取這些屬性,例如:如果想要獲取Class的name屬性,可以按如下方法獲取:
Class classPerson = Person.class;//printf("%s\n", classPerson->name);
//用這種方法已經(jīng)不能獲取name了 因?yàn)镺BJC2_UNAVAILABLE
constchar*cname? =class_getName(classPerson);
printf("%s", cname);//輸出:Person
函數(shù)的定義
對對象進(jìn)行操作的方法一般以object_開頭
對類進(jìn)行操作的方法一般以class_開頭
對類或?qū)ο蟮姆椒ㄟM(jìn)行操作的方法一般以method_開頭
對成員變量進(jìn)行操作的方法一般以ivar_開頭
對屬性進(jìn)行操作的方法一般以property_開頭開頭
對協(xié)議進(jìn)行操作的方法一般以protocol_開頭
根據(jù)以上的函數(shù)的前綴 可以大致了解到層級關(guān)系。
對于以objc_開頭的方法,則是runtime最終的管家,可以獲取內(nèi)存中類的加載信息,類的列表,關(guān)聯(lián)對象和關(guān)聯(lián)屬性等操作。
例如:使用runtime對當(dāng)前的應(yīng)用中加載的類進(jìn)行打印,別被嚇一跳。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
unsignedintcount =0;
Class*classes = objc_copyClassList(&count);for(inti =0; i < count; i++) {constchar*cname =class_getName(classes[i]);
printf("%s\n", cname);
}
}
runtime應(yīng)用
發(fā)送消息
方法調(diào)用的本質(zhì),就是讓對象發(fā)送消息。
objc_msgSend,只有對象才能發(fā)送消息,因此以objc開頭.
使用消息機(jī)制前提,必須導(dǎo)入#import
消息機(jī)制簡單使用:
//創(chuàng)建person對象
Person *p =[[Person alloc] init];
//調(diào)用對象方法
[p eat];
//本質(zhì):讓對象發(fā)送消息
objc_msgSend(p, @selector(eat));
//調(diào)用類方法的方式:兩種
//第一種通過類名調(diào)用
[Person eat];
//第二種通過類對象調(diào)用
[[Personclass] eat];
//用類名調(diào)用類方法,底層會自動把類名轉(zhuǎn)換成類對象調(diào)用
//本質(zhì):讓類對象發(fā)送消息
objc_msgSend([Personclass], @selector(eat));
交換方法
交換方法實(shí)現(xiàn)的需求場景:自己創(chuàng)建了一個功能性的方法,在項(xiàng)目中多次被引用,當(dāng)項(xiàng)目的需求發(fā)生改變時,要使用另一種功能代替這個功能,要求是不改變舊的項(xiàng)目(也就是不改變原來方法的實(shí)現(xiàn))。
可以在類的分類中,再寫一個新的方法(是符合新的需求的),然后交換兩個方法的實(shí)現(xiàn)。這樣,在不改變項(xiàng)目的代碼,而只是增加了新的代碼 的情況下,就完成了項(xiàng)目的改進(jìn)。
交換兩個方法的實(shí)現(xiàn)一般寫在類的load方法里面,因?yàn)閘oad方法會在程序運(yùn)行前加載一次,而initialize方法會在類或者子類在 第一次使用的時候調(diào)用,當(dāng)有分類的時候會調(diào)用多次。
@implementationViewController- (void)viewDidLoad {
[super viewDidLoad];
//Do any additional setup after loading the view, typically from a nib.
//需求:給imageNamed方法提供功能,每次加載圖片就判斷下圖片是否加載成功。//步驟一:先搞個分類,定義一個能加載圖片并且能打印的方法+ (instancetype)imageWithName:(NSString *)name;
//步驟二:交換imageNamed和imageWithName的實(shí)現(xiàn),就能調(diào)用imageWithName,間接調(diào)用imageWithName的實(shí)現(xiàn)。
UIImage *image = [UIImage imageNamed:@"123"];
}@end@implementationUIImage (Image)
//加載分類到內(nèi)存的時候調(diào)用+ (void)load
{
//交換方法
//獲取imageWithName方法地址Method imageWithName =class_getClassMethod(self, @selector(imageWithName:));
//獲取imageWithName方法地址Method imageName =class_getClassMethod(self, @selector(imageNamed:));
//交換方法地址,相當(dāng)于交換實(shí)現(xiàn)方式method_exchangeImplementations(imageWithName, imageName);
}
//不能在分類中重寫系統(tǒng)方法imageNamed,因?yàn)闀严到y(tǒng)的功能給覆蓋掉,而且分類中不能調(diào)用super.
//既能加載圖片又能打印
+ (instancetype)imageWithName:(NSString *)name
{
//這里調(diào)用imageWithName,相當(dāng)于調(diào)用
imageNameUIImage *image =[self imageWithName:name];if(image ==nil) {
NSLog(@"加載空的圖片");
}returnimage;
}@end
類\對象的關(guān)聯(lián)對象
關(guān)聯(lián)對象不是為類\對象添加屬性或者成員變量(因?yàn)樵谠O(shè)置關(guān)聯(lián)后也無法通過ivarList或者propertyList取得)?,而是為類添加一個相關(guān)的對象,通常用于存儲類信息,例如存儲類的屬性列表數(shù)組,為將來字典轉(zhuǎn)模型的方便。
使用方式一:給分類添加屬性
@implementationViewController- (void)viewDidLoad {
[super viewDidLoad];
//Do any additional setup after loading the view, typically from a nib.
//給系統(tǒng)NSObject類動態(tài)添加屬性
nameNSObject*objc =[[NSObject alloc] init];
objc.name=@"小碼哥";
NSLog(@"%@",objc.name);
}@end
//定義關(guān)聯(lián)的
keystaticconstchar*key ="name";@implementationNSObject (Property)- (NSString *)name
{
//根據(jù)關(guān)聯(lián)的key,獲取關(guān)聯(lián)的值。
returnobjc_getAssociatedObject(self, key);
}
- (void)setName:(NSString *)name
{
//第一個參數(shù):給哪個對象添加關(guān)聯(lián)//第二個參數(shù):關(guān)聯(lián)的key,通過這個key獲取//第三個參數(shù):關(guān)聯(lián)的value
//第四個參數(shù):關(guān)聯(lián)的策略objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}@end
使用方式二:給對象添加關(guān)聯(lián)對象。
比如alertView,一般傳值,使用的是alertView的tag屬性。我們想把更多的參數(shù)傳給alertView代理:
/**
*? 刪除點(diǎn)擊
*? @param recId? ? ? ? 購物車ID*/- (void)shopCartCell:(BSShopCartCell *)shopCartCell didDeleteClickedAtRecId:(NSString *)recId
{
UIAlertView*alert = [[UIAlertView alloc] initWithTitle:@""message:@"確認(rèn)要刪除這個寶貝"delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"確定", nil];
//傳遞多參數(shù)objc_setAssociatedObject(alert,"suppliers_id",@"1", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(alert,"warehouse_id",@"2", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
alert.tag=[recId intValue];
[alert show];
}/**
*? 確定刪除操作*/- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {if(buttonIndex ==1) {
NSString*warehouse_id = objc_getAssociatedObject(alertView,"warehouse_id");
NSString*suppliers_id = objc_getAssociatedObject(alertView,"suppliers_id");
NSString*recId = [NSString stringWithFormat:@"%ld",(long)alertView.tag];
}
}
objc_setAssociatedObject方法的參數(shù)解釋:
第一個參數(shù)id object, 當(dāng)前對象
第二個參數(shù)const void *key, 關(guān)聯(lián)的key,是c字符串
第三個參數(shù)id value, 被關(guān)聯(lián)的對象的值
第四個參數(shù)objc_AssociationPolicy policy關(guān)聯(lián)引用的規(guī)則
動態(tài)添加方法
開發(fā)使用場景:如果一個類方法非常多,加載類到內(nèi)存的時候也比較耗費(fèi)資源,需要給每個方法生成映射表,可以使用動態(tài)給某個類,添加方法解決。
經(jīng)典面試題:有沒有使用performSelector,其實(shí)主要想問你有沒有動態(tài)添加過方法。
簡單使用:
@implementationViewController- (void)viewDidLoad {
[super viewDidLoad];//Do any additional setup after loading the view, typically from a nib.Person*p =[[Person alloc] init];
//默認(rèn)person,沒有實(shí)現(xiàn)eat方法,可以通過performSelector調(diào)用,但是會報(bào)錯。
//動態(tài)添加方法就不會報(bào)錯[p performSelector:@selector(eat)];
}@end@implementationPerson
//void(*)()
//默認(rèn)方法都有兩個隱式參數(shù),voideat(idself,SEL sel)
{
NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
//當(dāng)一個對象調(diào)用未實(shí)現(xiàn)的方法,會調(diào)用這個方法處理,并且會把對應(yīng)的方法列表傳過來.
//剛好可以用來判斷,未實(shí)現(xiàn)的方法是不是我們想要動態(tài)添加的方法+(BOOL)resolveInstanceMethod:(SEL)sel
{if(sel ==@selector(eat)) {//動態(tài)添加eat方法
//第一個參數(shù):給哪個類添加方法
//第二個參數(shù):添加方法的方法編號
//第三個參數(shù):添加方法的函數(shù)實(shí)現(xiàn)(函數(shù)地址)
//第四個參數(shù):函數(shù)的類型,(返回值+參數(shù)類型) v:void @:對象->self :表示SEL->_cmdclass_addMethod(self, @selector(eat), eat,"v@:");
}return[super resolveInstanceMethod:sel];
}@end
面試題
說說什么是runtime
1>OC 是一個全動態(tài)語言,OC 的一切都是基于 Runtime 實(shí)現(xiàn)的
平時編寫的OC代碼, 在程序運(yùn)行過程中, 其實(shí)最終都是轉(zhuǎn)成了runtime的C語言代碼, runtime算是OC的幕后工作者
比如:
OC :
[[Person alloc] init]
runtime :
objc_msgSend(objc_msgSend("Person","alloc"),"init")
2>runtime是一套比較底層的純C語言API, 屬于1個C語言庫, 包含了很多底層的C語言API
3>runtimeAPI的實(shí)現(xiàn)是用 C++ 開發(fā)的(源碼中的實(shí)現(xiàn)文件都是mm),是一套蘋果開源的框架
使用過runtime嗎,用它來做什么
本文二、三部分。
參考: