iOS KVC (九) KVC模型转化(1) 模型打印 desc

2018-05-18  本文已影响30人  奔跑吧小蚂蚁

iOS KVC(一)基本了解
iOS KVC (二) 不可不知的赋值深层次原理
iOS KVC (三)不可不知的取值深层次原理
iOS KVC (四)keyPath的深度解析
iOS KVC (五)KVC几种典型的异常处理
iOS KVC (六) KVC容器类及深层次原理
iOS KVC(七) KVC正确性的验证
iOS KVC (八) KVC几种常见应用
iOS KVC (九) KVC模型转化(1) 模型打印 description, debugDescription
iOS KVC (十)模型转换(2)模型转换

本章主要讲解两个方法,其中也用到一些runtime 的方法。runtime后续必不可少会讲。直接上代码。

直接上代码

1.Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic,strong)NSString *name;
@property (nonatomic,assign)int age;


@end
2.Person.m

#import "Person.h"
#import <objc/runtime.h>
@implementation Person

- (NSString *)description{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //得到当前class的所有属性
    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]?:[NSNull null];//此处注意不能为nil 字典中尽量不要出现nil
        [dic setObject:value forKey:name];
    }
    free(properties);
    return [NSString stringWithFormat:@"description:<%@:%p> -- %@",[self class],self,dic];
}

- (NSString *)debugDescription{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //得到当前class的所有属性
    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]?:[NSNull null];//此处注意不能为nil 字典中尽量不要出现nil
        [dic setObject:value forKey:name];
    }
    free(properties);
    return [NSString stringWithFormat:@"debugDescription:<%@:%p> -- %@",[self class],self,dic];
}

@end
3.ViewController.m
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    Person *p = [[Person alloc]init];
    p.name = @"小明";
    p.age = 10;
    NSLog(@"p:%@",p);
}

打印数据:

2018-05-18 17:54:09.925353+0700 KVC[44115:1324816] p:description:<Person:0x604000031fe0> -- {
    age = 10;
    name = "\U5c0f\U660e";
}

总结:当我们对p进行打印时会直接触发“description”方法,那么“debugDescription”在什么时间调用,请看下图


断点打印.png

总结:
由上图我们可以看到,当对p进行打印的时候,直接触发调用了“description”,而我们对p进行控制台打印的时候 会触发“debugDescription”函数,已经很明白了 ,不需要进行解释了。

精彩在后面~

上一篇下一篇

猜你喜欢

热点阅读