运行时机制重写descrption实现实体模型数据打印查看

使用前打印实体模型时,结果是这样的

(lldb) po self.userModel
<SXLoginModel: 0x7fb08bc36aa0>

使用后打印实体模型时,结果是这样的

(lldb) po [self.userModel descriptionShow]

deptName : 南京校区;
lastSigninTime : 2018-07-13 16:16:56;
roleList : (
    "<SXRoleModel: 0x600000284060>"
);
sex : 2;
source : 1;
state : 1;
xiaoNengId : liuluqing;
zuoXiId : ;
(lldb) po [self.userModel.roleList.firstObject descriptionShow]

descn : (null);
roleId : 2e34ff21224541d;
roleName : 中端军团长;
state : 1;

代码实现

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface NSObject (SYCategory)

/// 实体模型属性打印
- (NSString *)descriptionShow;

@end

#import "NSObject+SYCategory.h"
#import <objc/runtime.h>

@implementation NSObject (SYCategory)

/// 实体模型属性打印
- (NSString *)descriptionShow
{
    NSString *message = @"\n";
    unsigned int outCount;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (int i = 0; i < outCount; i ++)
    {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if (propName)
        {
            NSString *key = [NSString stringWithCString:propName encoding:[NSString defaultCStringEncoding]];
            id value = [self valueForKey:key];
            message = [message stringByAppendingFormat:@"%@ : %@;\n", key, value];
        }
    }
    free(properties);
    return message;
}

@end

猜你喜欢

转载自blog.csdn.net/potato512/article/details/81033872