目录

Description方法和NSLog函数

1. description 方法是 NSObject 自带的方法,包括类方法和对象方法

1
2
+ (NSString *)description; // 默认返回 类名
- (NSString *)description; // 默认返回 <类名:内存地址>

2.默认情况下利用 NSLog 和 %@ 输出对象的时返回的就是类名和内存地址

3.修改 NSLog 和 %@ 的默认输出:重写类对象或者实例对象的 description 方法即可。因为 NSLog 函数进行打印的时候会自动调用 description 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/******************************** Person.h文件*********************************/
#import <Foundation/Foundation.h>

@interface Person : NSObject

+ (NSString *)description;
- (NSString *)description;

@property int age;
@property NSString *name;

@end



/******************************** Person.m文件*********************************/
#import "Person.h"
@implementation Person

#pragma mark 类对象输出的结果
+ (NSString *)description
{
    return @"AAA";
}


#pragma mark 实例对象输出的结果
- (NSString *)description
{
    // NSLog(@"%@",self); 引发死循环
    return [NSString stringWithFormat:@"name = %@ age = %d",_name,_age];
}
@end


/******************************** main.m文件***********************************/
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
    Class c = [Person class];
    NSLog(@"%@",c);

    Person *person = [[Person alloc] init];
    person.name = @"John";
    person.age = 20;

    // 执行NSLog函数的时候会调用description方法默认返回<类名/对象名: 地址>
    NSLog(@"%@",person);

}


/**************************** 丰富日志输出 **********************************/
#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[])
{
    Person *person = [[Person alloc] init];

    // 打印person对象地址
    NSLog(@"%@",person); // <Person: 0x100200ae0>
    // 打印person指针的地址
    NSLog(@"%p",person); // 0x100200ae0 对象和指针地址一致

    // 指针变量的地址
    NSLog(@"%p",&person);// 0x7fff5fbff8e8

    // NSLog不能%s无法输出带有中文的文件路径,可以用c语言中的printf和%s来代替
    // NSLog(@"%s",__FILE__);
    printf("%s",__FILE__);

    // 输出当前方法
    NSLog(@"%s",__FUNCTION__);  // 返回 main

}