Improved logging in 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 _cmd implicit
argument which gives the selector of the current method, and functions for converting selectors and classes to strings. You can use these in your NSLog statements to provide
useful context during debugging or error handling.
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.
|
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. |
|
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. |
本文介绍了如何在Objective-C中利用预处理器宏和特定表达式增强日志记录,以包含当前方法名、行号等上下文信息,从而提高调试效率。
2216

被折叠的 条评论
为什么被折叠?



