iOS_黑(1)_NSObject自动生成description

一.说明

功能:
自动生成属性在- (NSString *)description方法里
对于json解析创建的model,在创建模型的时候,能方便查看

二.内容

.h

#import 

@interface BaseObject : NSObject

@end

.m


#import "BaseObject.h"

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:@"------------"];
    return str;
}

三.使用

1.创建一个BaseObject的类添加上面代码
2.使用时,继承BaseObject这个类就可以了

你可能感兴趣的:(iOS_黑(1)_NSObject自动生成description)