#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];
}
很多時(shí)候,我們?cè)跀帱c(diǎn)調(diào)試的時(shí)候庸疾,并不是使用NSLog(@"%@",model);來(lái)打印模型,而是通過(guò)po這個(gè)命令,我們需要重寫debugDescription方法而不是description方法
debugDescription方法只會(huì)在調(diào)試po的時(shí)候調(diào)用,而在代碼中打印不會(huì)調(diào)用业踢。但是我們需要在每個(gè)模型中都重寫這個(gè)方法,而且代碼都不一樣礁扮,肯定受不了知举。我的解決方式是寫一個(gè)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"; // 默認(rèn)值為nil字符串
[dictionary setObject:value forKey:name];
}
free(properties);
return [NSString stringWithFormat:@"<%@: %p> -- %@", [self class], self, dictionary];
}
@end