前言:最近在读Effective Objective-C 2.0 ,看到有讲解description方法,总结一下写出来
Pragma mark — 直接上代码,创建一个testObject类,给两个属性:name和money
#import <Foundation/Foundation.h>
@interface testObject : NSObject
/**<#注释#>*/
@property (nonatomic , copy) NSString * name;
/**<#注释#>*/
@property (nonatomic , copy) NSString * money;
-(instancetype)initWithName:(NSString *)name money:(NSString *)money;
@end
#import "testObject.h"
@implementation testObject
-(instancetype)initWithName:(NSString *)name money:(NSString *)money{
self = [super init];
if (self) {
_name = name;
_money = money;
}
return self;
}
Pragma mark — NO.2 重写方法之前看打印效果和arr打印对比
- (void)viewDidLoad {
[super viewDidLoad];
//数组
NSArray *arr = @[@"name",@"type"];
NSLog(@"arr = %@",arr);
//自己的类
testObject *test1 = [[testObject alloc]initWithName:@"jiangjun" money:@"100"];
NSLog(@"test1 = %@",test1);
}
#打印结果
arr = (
name,
type
)
test1 = <testObject: 0x608000023f20>
从上可以看出对于arr来说打印了详细信息,而我们自己的类只打印了类型名和地址。
Pragma mark — NO.3 重写方法后,打印结果查看
//重写description方法---最简单的打印
- (NSString *)description{
//我们重写时,还是要打印那个类名,地址,这样会更加清晰
return [NSString stringWithFormat:@"%@ : %p, %@,%@",[self class],self,_name,_money];
}
//打印结果
arr = (
name,
type
)
test1 = testObject : 0x60000003fde0, jiangjun,100
#重写一个更清晰的打印效果
//封装为字典的打印
-(NSString *)description{
return [NSString stringWithFormat:@"%@ : %p , %@",[self class],self,@{@"name":_name,@"money":_money}];
}
//打印结果—更加一目了然
test1 = testObject : 0x600000030e20 , {
money = 100;
name = jiangjun;
}