#import <objc/runtime.h>
// 打印一个实例对象中的属性与值,包括在父类中的
- (void)print_Self_Properties {
// DEBUG 模式下打印日志,当前行
#ifdef DEBUG
unsigned int count = 0;
Class gc_class = [self class];
GCLog(@"统计开始 ⌛️")
NSMutableArray *key_array = [[NSMutableArray alloc] init];
NSMutableArray *target_array = [[NSMutableArray alloc] init];
while (gc_class) {
// 获取类的属性列表
objc_property_t *properties = class_copyPropertyList(gc_class, &count);
for (NSInteger index = 0; index < count; index++) {
// 获取属性的名称
objc_property_t property = properties[index];
//const char *property_name = property_getName(property);
NSString *property_name = [NSString stringWithCString:property_getName(property)
encoding:NSUTF8StringEncoding];
@try {
// 获取属性对应的值
id value = [self valueForKey:property_name];
if (value) {
if (![key_array containsObject:property_name]) {
[key_array addObject:property_name];
NSString *key_object = NSStringFormat(@"%@ = %@", property_name, value);
if ([value isKindOfClass:[NSString class]]) {
//[target_array addObject:key_object];
}
else if ([value isKindOfClass:[@(YES) class]]) {
[target_array addObject:key_object];
}
else if ([value isKindOfClass:[NSNumber class]]) {
//[target_array addObject:key_object];
}
else if ([value isKindOfClass:[@(CGRectZero) class]]) {
//[target_array addObject:key_object];
}
else if ([value isKindOfClass:[@(CGSizeZero) class]]) {
//[target_array addObject:key_object];
}
}
}
}
@catch (NSException *exception) {
}
}
// 释放内存
free(properties);
// 将父类作为当前类继续循环
gc_class = class_getSuperclass(gc_class);
}
if (target_array.count) {
// 排序
NSArray *sorted_array = [target_array sortedArrayUsingSelector:@selector(compare:)];
for (NSInteger index = 1; index <= sorted_array.count; index++) {
GCLog(@"键值对[%03ld]:%@", index, sorted_array[index - 1]);
}
}
GCLog(@"统计结束
标签:父类,Apple,value,与值,key,array,property,class,target
From: https://blog.51cto.com/u_15318120/8003303