一.说明
功能:
自动生成属性在- (NSString *)description方法里
对于json解析创建的model,在创建模型的时候,能方便查看
二.内容
.h
#import <Foundation/Foundation.h>
@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:@"------<End>------"];
return str;
}
三.使用
1.创建一个BaseObject的类添加上面代码
2.使用时,继承BaseObject这个类就可以了