iOS-runtime__運(yùn)行時(shí)機(jī)制—概述

Runtime的概念

1、Runtime是一套底層的C語言API(包含強(qiáng)大的C語言數(shù)據(jù)類型和函數(shù))

2、OC代碼都是基于Runtime實(shí)現(xiàn)的,即編寫的OC代碼最終都會(huì)轉(zhuǎn)成Runtime的代碼,

例如:?

?HCPerson *person = [HCPerson alloc] init];?

[person setAge:10]; //這句會(huì)轉(zhuǎn)換成

objc_msgSend(person,@selector(setAge:),20);

Runtime的作用

1、獲取類的私有變量?

#import// Ivar : 成員變量

unsigned int count = 0;

// 獲得所有的成員變量

Ivar *ivars = class_copyIvarList([HCPerson class], &count);

for (int i = 0; i<count;i++){

// 取得i位置的成員變量?

Ivar ivar = ivars[i];

const char *name = ivar_getName(ivar);

const char *type = ivar_getTypeEncoding(ivar);

NSLog(@"%d %s %s", i, name, type);

}

2、動(dòng)態(tài)產(chǎn)生類,成員變量和方法

3、動(dòng)態(tài)修改類,成員變量和方法

4、對(duì)換兩個(gè)方法的實(shí)現(xiàn)(swizzle)

例如:如果想要對(duì)iOS7以上和iOS7以下的圖片進(jìn)行適配,不同系統(tǒng)版本顯示不同的圖片,則可利用swizzle來實(shí)現(xiàn)

實(shí)現(xiàn)方法:

1.自定義UIImage的類imageWithName:方法,在該方法內(nèi)進(jìn)行系統(tǒng)版本號(hào)的判斷,來顯示不同的圖片

2.將imageWithName:方法和系統(tǒng)的imageNamed:方法進(jìn)行對(duì)換,這樣,一旦調(diào)用系統(tǒng)的imageNamed:方法,便會(huì)執(zhí)行自定義的imageWithName:方法,進(jìn)行判斷,顯示不同的圖片

/**

*? 只要分類被裝載到內(nèi)存中,就會(huì)調(diào)用1次

*/

+ (void)load

{

//獲取類方法

Method otherMehtod = class_getClassMethod(self, @selector(imageWithName:));

Method originMehtod = class_getClassMethod(self, @selector(imageNamed:));

// 交換2個(gè)方法的實(shí)現(xiàn)

method_exchangeImplementations(otherMehtod, originMehtod);

}

+ (UIImage *)imageWithName:(NSString *)name

{

BOOL iOS7 = [[UIDevice currentDevice].systemVersion floatValue] >= 7.0;

UIImage *image = nil;

if (iOS7) {

NSString *newName = [name stringByAppendingString:@"_os7"];

image = [UIImage imageWithName:newName];

}

if (image == nil) {

image = [UIImage imageWithName:name];

}

return image;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容