#import "RunTime.h"
typedef struct objc_property *objc_property_t;
@implementation RunTime
//实现单例
+ (NSMutableDictionary *)defaultMyproperty{
//添加线程锁
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if(Myproperty ==nil){
Myproperty=[NSMutableDictionary dictionary];
}
});
return Myproperty;
}
//返回自己这个类的所有属性
- (NSArray *)allProperties {
unsigned int count;
// 获取类的所有属性
// 如果没有属性,则count为0,properties为nil
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (NSUInteger i = 0; i < count; i++) {
// 获取属性名称
const char *propertyName = property_getName(properties[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
[propertiesArray addObject:name];
}
// 注意,这里properties是一个数组指针,是C的语法,
// 我们需要使用free函数来释放内存,否则会造成内存泄露
free(properties);
return propertiesArray;
}
//返回指定某个类的所有属性
+ (NSArray *)allPropertiesFromObject:(id)object{
unsigned int count;
objc_property_t *properties = class_copyPropertyList([object class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (NSUInteger i = 0; i < count; i++) {
const char *propertyName = property_getName(properties[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
[propertiesArray addObject:name];
}
free(properties);
return propertiesArray;
}
//返回自己这个类的所有属性名和属性值
- (NSDictionary *)allPropertyNamesAndValues{
NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *name = property_getName(property);
// 得到属性名
NSString *propertyName = [NSString stringWithUTF8String:name];
// 获取属性值
id propertyValue = [self valueForKey:propertyName];
if (propertyValue && propertyValue != nil) {
[resultDict setObj