一、前言
苹果有些api是不公开的,但是我们可以利用setValue forKeyPaths:这个方法对内部属性进行访问。那么前提是我们需要知道这个“keyPaths”,所以再一次利用runtime的方法
二、打印成员变量名
unsigned int count = 0;
Ivar *ivars = class_copyIvarList(self.class, &count);
for(int i = 0; i < count; i++)
{
const char *str = ivar_getName(ivars[i]);
NSString *name = [NSString stringWithUTF8String:str];
// 输出 属性--属性值
DebugLog(@"%@--%@", [NSString stringWithUTF8String:str], [self valueForKeyPath:name]);
}
三、打印属性名
这里跟打印成员变量名是差不多的。
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList(self.class, &count);
for(int i = 0; i < count; i++)
{
const char *str = property_getName(propertys[i]);
NSString *name = [NSString stringWithUTF8String:str];
// 输出 属性--属性值
DebugLog(@"%@--%@", [NSString stringWithUTF8String:str], [self valueForKeyPath:name]);
}
四、打印方法名
unsigned int count = 0;
Method *methods = class_copyMethodList(self.class, &count);
for(int i = 0; i < count; i++)
{
SEL sel = method_getName(methods[i]);
DebugLog(@"%@", NSStringFromSelector(sel));
}
五、总结
可以发现runtime里方法命名是很有规律的,如果要操作class,就class_开头,操作Method,就method_开头。
六、使用场景
- 归档解档
- 字典转模型
- KVC