在调试时,我们经常用到输出model,查看数据是否正确,还会在控制台"po 模型"操作,一般输出都是这样的格式的:
person is <Person: 0x608000034300>
这里添加一种解决方法:
1> 解决NSLog(@"person is %@", p)打印model内容:
// // Person.m // Demo1 // // Created by 思 彭 on 2017/7/31. // Copyright © 2017年 思 彭. All rights reserved. // #import "Person.h" #import <objc/runtime.h> @implementation Person // 通过重写模型的description方法,实现打印Model - (NSString *)description { // 初始化一个字典 NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; // 得到当前classs的所有属性 uint count; objc_property_t *properties = class_copyPropertyList([self class], &count); for (int i = 0; i < count; i++) { // 循环并用kvc得到每个属性的值 objc_property_t property = properties[i]; NSString *name = @(property_getName(property)); id value = [self valueForKey:name] ? : nil; // 默认值为nil字符串 [dictionary setObject:value forKey:name]; } // 释放 free(properties); // return return [NSString stringWithFormat:@"<%@: %p> -- %@",[self class], self, dictionary]; } @end
2>po model输出model内容:
// // NSObject+DebugDescription.m // Demo1 // // Created by 思 彭 on 2017/7/31. // Copyright © 2017年 思 彭. All rights reserved. // #import "NSObject+DebugDescription.h" #import <objc/runtime.h> @implementation NSObject (DebugDescription) - (NSString *)debugDescription { if ([self isKindOfClass:[NSArray class]] || [self isKindOfClass:[NSNumber class]] || [self isKindOfClass:[NSString class]]) { return self.debugDescription; } // 初始化一个字典 NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; // 得到当前classs的所有属性 uint count; objc_property_t *properties = class_copyPropertyList([self class], &count); for (int i = 0; i < count; i++) { // 循环并用kvc得到每个属性的值 objc_property_t property = properties[i]; NSString *name = @(property_getName(property)); id value = [self valueForKey:name] ? : nil; // 默认值为nil字符串 [dictionary setObject:value forKey:name]; } // 释放 free(properties); // return return [NSString stringWithFormat:@"<%@: %p> -- %@",[self class], self, dictionary]; } @end
使用:
// // ViewController.m // Demo1 // // Created by 思 彭 on 2017/7/31. // Copyright © 2017年 思 彭. All rights reserved. // #import "ViewController.h" #import "Person.h" #import "NSObject+DebugDescription.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person *p = [Person new]; p.name = @"sis"; p.age = 30; p.habit = @"singer, dancer"; NSLog(@"person is %@", p); // person is <Person: 0x608000034300> } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
注意:
在使用控制器类需要导入该Category哟!!!