Runtime的概念
1徘键、Runtime是一套底層的C語言API(包含強(qiáng)大的C語言數(shù)據(jù)類型和函數(shù))
2砖茸、OC代碼都是基于Runtime實(shí)現(xiàn)的,即編寫的OC代碼最終都會轉(zhuǎn)成Runtime的代碼峦筒,
例如:?
?HCPerson *person = [HCPerson alloc] init];?
[person setAge:10]; //這句會轉(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锄列、動態(tài)產(chǎn)生類图云,成員變量和方法
3、動態(tài)修改類邻邮,成員變量和方法
4竣况、對換兩個方法的實(shí)現(xiàn)(swizzle)
例如:如果想要對iOS7以上和iOS7以下的圖片進(jìn)行適配,不同系統(tǒng)版本顯示不同的圖片筒严,則可利用swizzle來實(shí)現(xiàn)
實(shí)現(xiàn)方法:
1.自定義UIImage的類imageWithName:方法丹泉,在該方法內(nèi)進(jìn)行系統(tǒng)版本號的判斷,來顯示不同的圖片
2.將imageWithName:方法和系統(tǒng)的imageNamed:方法進(jìn)行對換鸭蛙,這樣摹恨,一旦調(diào)用系統(tǒng)的imageNamed:方法,便會執(zhí)行自定義的imageWithName:方法娶视,進(jìn)行判斷晒哄,顯示不同的圖片
/**
*? 只要分類被裝載到內(nèi)存中,就會調(diào)用1次
*/
+ (void)load
{
//獲取類方法
Method otherMehtod = class_getClassMethod(self, @selector(imageWithName:));
Method originMehtod = class_getClassMethod(self, @selector(imageNamed:));
// 交換2個方法的實(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;
}