IOS development-log printing (common)
Q: How do I print the current function and row number?
A: Some pre-compiled macros can be used as printing parameters to print the current function and row number. For example:
NSLog(@"%s:%d obj=%@", __func__, __LINE__, obj);
NSLog (@ "% s: % d obj = % @", _ func __, _ LINE __, self); // output style: // 17:13:17. 852 justTest [15079: 613] //-[ViewController viewDidLoad]: 38 obj =
Both func and line are pre-compiled macros, which are replaced with the current function and the current row number respectively during compilation. The following are some macros that are commonly used to print logs.
Macro |
Description |
_ Func __ |
Print the current function or method, c string |
_ LINE __ |
Print the current row number, an integer |
_ FILE __ |
Print the current file path, c string |
_ PRETTY_FUNCTION __ |
Print the current function or method (including the parameter type in C ++), c string |
Q: How do I print a class name, message name, and current stack information?
A: You can use the following methods to dynamically obtain the information at runtime.
Code |
Description |
NSStringFromSelector (SEL) |
Obtain the selector name |
NSStringFromSelector (_ cmd) |
Get the current method name |
NSStringFromClass ([object class]) |
Obtains the class name of an object. |
[NSThread callStackSymbols] |
Gets the stack of the current thread, which is an NSArry that contains all function names in the stack. |
Q: How to print logs to a file?
A: You can use the freopen function to redirect standard output and standard error files. Because the printf function prints to the standard output (stdout), and The NSLog function prints to the standard error (stderr. Redirecting stdout and stderr to a file will make them print logs to a file.
freopen("/tmp/log.txt", "a+", stdout);freopen("/tmp/log.txt", "a+", stderr);