首先,创建一个person类,代码如下:
XGPerson.h
#import <Foundation/Foundation.h>
@interface XGPerson : NSObject
/// 年龄
@property (nonatomic, copy) NSString *age;
/// 性别
@property (nonatomic, copy) NSString *sex;
- (void)text1;
@end
XGPerson.m
#import "XGPerson.h"
@implementation XGPerson
- (void)text1 {
NSLog(@"%s",__func__);
}
- (void)text2 {
NSLog(@"%s",__func__);
}
@end
在控制器里获取并打印该类的成员变量、属性和方法,代码如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 获取成员变量
unsigned int ivarCount = 0;
Ivar *ivars = class_copyIvarList([XGPerson class], &ivarCount);
for (int i = 0; i < ivarCount; i++) {
Ivar ivar = ivars[i];
NSLog(@"第%d个成员变量:%s",i,ivar_getName(ivar));
}
free(ivars);
// 获取属性
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([XGPerson class], &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = propertyList[i];
NSLog(@"第%d个属性:%s",i,property_getName(property));
}
// 获取方法列表
unsigned int methodCount = 0;
Method *methods = class_copyMethodList([XGPerson class], &methodCount);
for (int i = 0; i < methodCount; i++) {
Method method = methods[i];
NSLog(@"第%d个方法:%s",i, sel_getName(method_getName(method)));
}
}
此时控制台输出如下: