iOS开发中天控制台打交道,一些增强输出小技巧,可用获得
从Apple 官方文档中,可以看到苹果对日志输出的重视,总结了一些log增强的宏供我们使用。
一、Improved logging in Objective-C简单翻译
内容如下:
Technical Q&A QA1669 Improved logging in Objective-C
技术问题与回答QA1669 Objective-C 中日志增强
Q: How can I add context information - such as the current method or line number - to my logging statements?
问题:我在日志输出语句中,怎样添加一些上下文信息呢,比如当前的方法名是什么,当前的代码行数是多少?
A:The C preprocessor provides a number of standard macros that give you information about the current file, line number, or function. Additionally, Objective-C has the _cmdimplicit argument which gives the selector of the current method, and functions for converting selectors and classes to strings. You can use these in yourNSLogstatements to provide useful context during debugging or error handling.
回答:C 的预处理 提供了很多标准宏定义,这些宏定义可以给你想要的相关信息,比如当前的源文件,代码行,或者当前的函数。另外,Objective-C拥有“_cmdimplicit”,可以把当前的方法或者函数、类转换为字符串,传递给选择器。你可以在你的NSLog输出语句中使用提供的这些有用的上下文来进行调试和错误处理。
Listing 1 Example of logging the current method and line number. Paste it into your project, and see what it prints!
一个输出当前方法和代码行的例子,粘贴到你的工程里,看他们输出什么吧
NSMutableArray *someObject = [NSMutableArray array];
NSLog(@"%s:%d someObject=%@", __func__, __LINE__, someObject);
[someObject addObject:@"foo"];
NSLog(@"%s:%d someObject=%@", __func__, __LINE__, someObject);
The following tables list the most popular macros and expressions which might be useful in your logging statements.
下面的表格,列出了最常使用的宏定义和语句,在你使用日志输出语句的时候可用有帮助。
Table 1Preprocessor macros and for logging in C/C++/Objective-C.
Macro Format Specifier Description
__func__ %s Current function signature.
__LINE__ %d Current line number in the source code file.
__FILE__ %s Full path to the source code file.
__PRETTY_FUNCTION__ %s Like __func__, but includes verbose type information in C++ code.
Table 2Expressions for logging in Objective-C.
Expression Format Specifier Description
NSStringFromSelector(_cmd) %@ Name of the current selector.
NSStringFromClass([self class]) %@ Name of the current object's class.
[[NSString stringWithUTF8String:__FILE__] lastPathComponent] %@ Name of the source code file.
[NSThread callStackSymbols] %@ NSArray of the current stack trace as programmer-readable strings. For debugging only, do not present it to end users or use to do any logic in your program.
二、使用C语言语法,在Xcode工程中进行日志输出
附一个使用C语法输出的例子:
const char * 的类型是 字符产量数组 用%s
%s 字符串 (但C语言中没有字符串类型,也就是说没有变量能直接存字符串,只能用数组,但数组输出时只能用%c 一个一个的输出)
NSLog(@"%s", __func__);
NSInteger j = strlen(__func__);
for (int i = 0; i < j; i++) {
printf("%c",__func__[i]);
}
输出结果:
2017-02-02 14:58:11.210 Day02TextFiled[5349:676054] -[ViewController clicked:]
-[ViewController clicked:]