#import <objc/runtime.h>
- (NSString *)description
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
uint count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = @(property_getName(property));
id value = [self valueForKey:name]?:@"nil";
[dictionary setObject:value forKey:name];
}
free(properties);
return [NSString stringWithFormat:@"<%@:%p> -- %@", [self class], self, dictionary];
}
很多时候,我们在断点调试的时候,并不是使用NSLog(@"%@",model);来打印模型,而是通过po这个命令,我们需要重写debugDescription方法而不是description方法
debugDescription方法只会在调试po的时候调用,而在代码中打印不会调用。但是我们需要在每个模型中都重写这个方法,而且代码都不一样,肯定受不了。我的解决方式是写一个NSObject的分类NSObject+DebugDescription并重写debugDescription,并处理了po其他类型的情况
#import "NSObject+DebugDescription.h"
#import <objc/runtime.h>
@implementation NSObject (DebugDescription)
- (NSString *)debugDescription
{
if ([self isKindOfClass:[NSArray class]] || [self isKindOfClass:[NSDictionary class]] || [self isKindOfClass:[NSNumber class]] || [self isKindOfClass:[NSString class]])
{
return self.debugDescription;
}
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
uint count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = @(property_getName(property));
id value = [self valueForKey:name]?:@"nil"; // 默认值为nil字符串
[dictionary setObject:value forKey:name];
}
free(properties);
return [NSString stringWithFormat:@"<%@: %p> -- %@", [self class], self, dictionary];
}
@end