生成description

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
static NSMutableDictionary *modelsDescription = nil;
@implementation BaseObject
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
modelsDescription = [NSMutableDictionary dictionary];
});
}
- (NSDictionary *)mapPropertiesToDictionary
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
Class cls = [self class];
uint ivarsCount = 0;
Ivar *ivars = class_copyIvarList(cls, &ivarsCount);
const Ivar *ivarsEnd = ivars + ivarsCount;
for (const Ivar *ivarsBegin = ivars; ivarsBegin < ivarsEnd; ivarsBegin++)
{
Ivar const ivar = *ivarsBegin;
NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
if ([key hasPrefix:@"_"]) key = [key substringFromIndex:1];
id value = [self valueForKey:key];
[dictionary setObject:value ? value : [NSNull null]
forKey:key];
}
if (ivars)
{
free(ivars);
}
return dictionary;
}
- (NSString *)description
{
NSMutableString *str = [NSMutableString stringWithFormat:@"------<%@>------n", NSStringFromClass([self class])];
NSDictionary *dic = [self mapPropertiesToDictionary];
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[str appendFormat:@"< %@ = %@ >n", key, obj];
}];
[str appendString:@"------<End>------"];
return str;
}

原文链接: http://blog.csdn.net/zhz459880251/article/details/52149603