class_copyIvarList 和 class_copyPropertyList的區(qū)別
新建一個類 MessageModel
1、在MessageModel.h文件中聲明屬性
@property (nonatomic, copy) NSString *sender;
2、在MessageModel.m文件中,實現(xiàn)類擴展并添加屬性
@interface MessageModel ()
@property (nonatomic, copy) NSString *sendTime;
@end
3、在MessageModel.m文件中的實現(xiàn)中添加成員變量
@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]);
}
輸入結(jié)果為

image.png
5、由此可見,class_copyIvarList獲取的是類中的成員變量,包括.h和extension中聲明屬性的成員變量,以及實現(xiàn)文件中{}內(nèi)的成員變量,而class_copyPropertyList獲取的則是.h和extension中聲明屬性。
6、引申,如果添加一個分類,在分類中添加一個屬性那么兩個打印結(jié)果是否有不同
創(chuàng)建一個分類MessageModel+Input并添加屬性,同時在.m文件通過runtime關(guān)聯(lián)屬性
@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
輸出結(jié)果如下

image.png
此時可以看到
property_list中多了 一個我們在分類中聲明的屬性inputName,但是在ivar_list中并沒有出現(xiàn)_inputName的成員變量,由此可以判斷class_copyIvarList獲取的是類中的成員變量,包括.h和extension中聲明屬性的成員變量,以及實現(xiàn)文件中{}內(nèi)的成員變量,而class_copyPropertyList獲取的則是.h和extension以及category中聲明屬性。也可以側(cè)面反應(yīng)分類可以添加屬性(需要自己實現(xiàn)setter和getter方法),但是不能添加成員變量。