-
class_copyIvarList是获取实例变量列表信息。
-
class_copyPropertyList是获取变量属性的信息。
代码如下
AppDelegate
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import <objc/runtime.h>
#import "MyClass.h"
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
Class myClass = [MyClass class];
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList(myClass, &count);
for (unsigned int i = 0; i < count; i++) {
objc_property_t property = propertyList[i];
const char *propertyName = property_getName(property);
NSLog(@"Property name: %s", propertyName);
}
unsigned int count1;
Ivar *ivarList = class_copyIvarList(myClass, &count1);
for (unsigned int i = 0; i < count1; i++) {
Ivar ivar = ivarList[i];
const char *ivarName = ivar_getName(ivar);
NSLog(@"Instance variable name: %s", ivarName);
}
free(propertyList);
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
Myclass
@interface MyClass : NSObject {
NSInteger myInteger;
NSString *myString;
}
@property(nonatomic, strong) NSString *propertyName;
@property(nonatomic, assign) NSInteger propertyNumber;
@end
@interface MyClass ()
@property(nonatomic, assign) NSInteger propertyNumber2;
@end
@implementation MyClass
@end
输出结果
Property name: propertyNumber2
Property name: propertyName
Property name: propertyNumber
Instance variable name: myInteger
Instance variable name: myString
Instance variable name: _propertyName
Instance variable name: _propertyNumber
Instance variable name: _propertyNumber2
项目测试地址:测试class_copyIvarList和class_copyPropertyList之间的区别