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 you |
本文介绍了如何在Objective-C中通过使用预处理器宏和_cmd隐含参数来添加当前方法和行号信息到日志声明,增强调试和错误处理能力。通过展示示例代码和常用表达式列表,读者可以轻松地在自己的项目中应用这些技巧。
1589

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



