今天博主有一個runtime高級的需求,遇到了一些困難點,在此和大家分享,希望能夠共同進步.
相信看了博主上一篇博文,各位對runtime都有了一定的理解,當面試官問你runtime是什么的時候,相信大家不會只說一個運行時就沒有詞了.那么當你說完了你對runtime的理解后,大部分面試官都會問你,你用過runtime嗎?
runtime是一項危險的技術,蘋果的官方文檔建議我們不要輕易使用runtime,但是最基本的用法我們還是應該掌握的,runtime的函數有很多,我們可以點入頭文件
objc/runtime.h中詳細查看
相關函數
1. 增加
增加函數:class_addMethod
增加實例變量:class_addIvar
增加屬性:@dynamic標簽,或者class_addMethod,因為屬性其實就是由getter和setter函數組成
增加PRotocol:class_addProtocol (說實話我真不知道動態增加一個protocol有什么用,-_-!!)
2. 獲取
獲取函數列表及每個函數的信息(函數指針、函數名等等):class_getClassMethod method_getName ...
獲取屬性列表及每個屬性的信息:class_copyPropertyList property_getName
獲取類本身的信息,如類名等:class_getName class_getInstanceSize
獲取變量列表及變量信息:class_copyIvarList
獲取變量的值
3. 替換
將實例替換成另一個類:object_setClass
替換類方法的定義:class_replaceMethod
4.其他常用方法:
交換兩個方法的實現:method_exchangeImplementations.
設置一個方法的實現:method_setImplementation.
其中最簡單的runtime應用要數用runtime查看類的屬性列表,方法列表,成員變量列表和協議列表,下面把代碼貼出來與大家分享.
unsigned int count;
//獲取屬性列表
objc_property_t *propertyList=class_copyPropertyList([self class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyname =property_getName(propertyList[i]);
NSLog(@"property-----%@", [NSString stringWithUTF8String:propertyname]);
}
//獲取方法列表
Method *methodList=class_copyMethodList([self class], &count);
for (unsigned int i; i<count; i++) {
Method method=methodList[i];
NSLog(@"method-----%@", NSStringFromSelector(method_getName(method)));
}
//獲取成員變量列表
Ivar *ivarList=class_copyIvarList([self class], &count);
for (unsigned int i; i<count; i++) {
Ivar myIvar=ivarList[i];
const char *ivarName=ivar_getName(myIvar);
NSLog(@"ivar------%@",[NSString stringWithUTF8String:ivarName]);
}
//獲取協議列表
__unsafe_unretained Protocol **protocolList=class_copyProtocolList([self class], &count);
for (unsigned int i; i<count; i++) {
Protocol *myProtocol=protocolList[i];
const char *protocolName=protocol_getName(myProtocol);
NSLog(@"protocol------%@",[NSString stringWithUTF8String:protocolName]);
}
當然還有一些更為復雜的應用這里就不多做闡述了,下面幾個博客會讓你更加理解runtime
http://www.cocoachina.com/ios/20150901/13173.html?utm_source=tuicool
http://www.cocoachina.com/ios/20150907/13336.html?utm_source=tuicool
http://hechen.info/2015/09/07/Understanding-the-Objective-C-Runtime/?utm_source=tuicool
http://www.tuicool.com/articles/MvM3ie?plg_nld=1&plg_uin=1&plg_auth=1&plg_nld=1&plg_usr=1&plg_vkey=1&plg_dev=1
http://www.tuicool.com/articles/uyaAZjM?plg_nld=1&plg_uin=1&plg_auth=1&plg_nld=1&plg_usr=1&plg_vkey=1&plg_dev=1
http://www.cocoachina.com/ios/20150824/13104.html?utm_source=tuicool
http://www.tuicool.com/articles/q2uqAjq?plg_nld=1&plg_uin=1&plg_auth=1&plg_nld=1&plg_usr=1&plg_vkey=1&plg_dev=1
http://www.cocoachina.com/cms/wap.php?plg_nld=1&action=article&id=12540&plg_auth=1&plg_uin=1&plg_dev=1&plg_nld=1&plg_usr=1&plg_vkey=1
http://www.jianshu.com/p/bd24c3f3cd0a?plg_nld=1&plg_uin=1&plg_auth=1&plg_nld=1&plg_usr=1&plg_vkey=1&plg_dev=1
http://www.tuicool.com/articles/YzeiEna?plg_nld=1&plg_uin=1&plg_auth=1&plg_nld=1&plg_usr=1&plg_vkey=1&plg_dev=1
新聞熱點
疑難解答