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问题