iOS 进阶 - RUNTIME 运行时
生活随笔
收集整理的這篇文章主要介紹了
iOS 进阶 - RUNTIME 运行时
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
什么是 RUNTIME ?
1.Runtime就是運行時,OC就是運行機制也就是在運行的時候的一些機制。其主要有消息機制。
2.對于C語言來說,函數調用在編譯的時候就會決定調用哪個函數;而對于OC的函數,是屬于動態調用過程的,在編譯的時候并不決定真正調用哪個函數,只有在真正運行的時候才會根據函數名稱去找到對應的函數來調用。
3.在編譯階段,OC可以調用任何函數,即使這個函數并未實現,只有存在聲明就不會報錯。而C語言在編譯階段調用未實現的方法是會報錯的。
?
如何 RUNTIME 通過獲取屬性和方法名?
【oschina】http://git.oschina.net/emo_lin/RUNTIME
1. 獲取該類中.h和.m中成員變量,可以通過 class_copyPropertyList 來實現。
// 獲取該類中.h和.m中成員變量,可以通過 class_copyPropertyList 來實現。 -(NSArray *)allPropertyies {unsigned int count;objc_property_t * property = class_copyPropertyList([self class], &count);NSMutableArray * propertyieArray = [NSMutableArray arrayWithCapacity:count];for (NSUInteger i = 0; i < count; i++) {const char * propertyName = property_getName(property[i]);NSString * name = [NSString stringWithUTF8String:propertyName];[propertyieArray addObject:name];}free(property);return propertyieArray; }2.獲取對象的有值的屬性名和屬性值,如果屬性名沒有值需要為其賦空。
// 獲取對象的有值的屬性名和屬性值,如果屬性名沒有值需要為其賦空。 - (NSDictionary *)allPropertyNamesAndValues {NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];unsigned int outCount;// 開辟內存空間objc_property_t *properties = class_copyPropertyList([self class], &outCount);for (int i = 0; i < outCount; i++) {objc_property_t property = properties[i];const char *name = property_getName(property);// 得到屬性名NSString *propertyName = [NSString stringWithUTF8String:name];// 獲取屬性值id propertyValue = [self valueForKey:propertyName];if (propertyValue && propertyValue != nil) {[resultDict setObject:propertyValue forKey:propertyName];}}// 釋放內存空間free(properties);return resultDict; }3. 獲取該類中的所有方法時,包括通過@property為成員變量自動生成的setter和getter方法,可以通過class_copyMethodList來實現。
// 獲取該類中的所有方法時,包括通過@property為成員變量自動生成的setter和getter方法,可以通過class_copyMethodList來實現。 - (void)allMethods {unsigned int outCount = 0;Method *methods = class_copyMethodList([self class], &outCount);for (int i = 0; i < outCount; ++i) {Method method = methods[i];// 獲取方法名稱,但是類型是一個SEL選擇器類型SEL methodSEL = method_getName(method);// 需要獲取C字符串const char *name = sel_getName(methodSEL);// 將方法名轉換成OC字符串NSString *methodName = [NSString stringWithUTF8String:name];// 獲取方法的參數列表int arguments = method_getNumberOfArguments(method);NSLog(@"方法名:%@, 參數個數:%d", methodName, arguments);}// 記得釋放free(methods); }4.獲取所有的私有成員變量,可以通過class_copyIvarList實現。
// 獲取所有的私有成員變量,可以通過class_copyIvarList實現。 - (NSArray *)allMemberVariables {unsigned int count = 0;Ivar *ivars = class_copyIvarList([self class], &count);NSMutableArray *results = [[NSMutableArray alloc] init];for (NSUInteger i = 0; i < count; ++i) {Ivar variable = ivars[i];const char *name = ivar_getName(variable);NSString *varName = [NSString stringWithUTF8String:name];[results addObject:varName];}free(ivars);return results; }?
?
?
?
轉載于:https://my.oschina.net/linweida/blog/742859
總結
以上是生活随笔為你收集整理的iOS 进阶 - RUNTIME 运行时的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cookie, LocalStorage
- 下一篇: 设计上如何避免EMC问题