class_copyIvarList 和 class_copyPropertyList的区别
新建一个类 MessageModel
1、在MessageModel.h文件中声明属性
@property (nonatomic, copy) NSString *sender;
2、在MessageModel.m文件中,实现类扩展并添加属性
@interface MessageModel ()
@property (nonatomic, copy) NSString *sendTime;
@end
3、在MessageModel.m文件中的实现中添加成员变量
@implementation MessageModel
{
NSString *timeInterval;
}
@end
4、ViewController中获取MessageModel的Ivar和Property
MessageModel *message = [[MessageModel alloc] init];
/// 获取 ivar
unsigned int ivarCount;
Ivar *ivar_list = class_copyIvarList(message.class, &ivarCount);
for (int i = 0; i < ivarCount; i++) {
Ivar ivar = ivar_list[i];
const char *cName = ivar_getName(ivar);
NSLog(@"--> ivar name: %@", [NSString stringWithUTF8String:cName]);
}
NSLog(@"\n\n");
/// 获取 property
unsigned int propertyCount;
objc_property_t *property_list = class_copyPropertyList(message.class, &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = property_list[i];
const char *cName = property_getName(property);
NSLog(@"--> property name: %@", [NSString stringWithUTF8String:cName]);
}
输入结果为

image.png
5、由此可见,class_copyIvarList获取的是类中的成员变量,包括.h和extension中声明属性的成员变量,以及实现文件中{}内的成员变量,而class_copyPropertyList获取的则是.h和extension中声明属性。
6、引申,如果添加一个分类,在分类中添加一个属性那么两个打印结果是否有不同
创建一个分类MessageModel+Input并添加属性,同时在.m文件通过runtime关联属性
@interface MessageModel (Input)
@property (nonatomic, copy) NSString *inputName;
@end
@implementation MessageModel (Input)
- (void)setInputName:(NSString *)inputName {
objc_setAssociatedObject(self, @selector(inputName), inputName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)inputName {
return objc_getAssociatedObject(self, @selector(inputName));
}
@end
输出结果如下

image.png
此时可以看到
property_list中多了 一个我们在分类中声明的属性inputName,但是在ivar_list中并没有出现_inputName的成员变量,由此可以判断class_copyIvarList获取的是类中的成员变量,包括.h和extension中声明属性的成员变量,以及实现文件中{}内的成员变量,而class_copyPropertyList获取的则是.h和extension以及category中声明属性。也可以侧面反应分类可以添加属性(需要自己实现setter和getter方法),但是不能添加成员变量。