NSLog调试技巧

苹果最近更新了一份关于调试的文档。现在把那些不熟悉的知识记录一下。


通过速写记法输出numbers

double myNumber = 7.7;
NSLog( @"number: %@", @ (myNumber) );

输出:

number: 7.7

输出环境信息

格式说明符 描述
__func__ %s 当前函数签名
__LINE__ %d 在源代码文件的当前行号
__FILE__ %s 源代码文件的完整路径
__PRETTY_FUNCTION__ %s 类似于__func__,但包括在C + +代码中的详细类型信息。

表达 格式说明符 描述
NSStringFromSelector(_cmd) %@ 当前选择器的名称。 
NSStringFromClass([self class]) %@ 当前对象类的名称。 
[[NSString stringWithUTF8String:__FILE__] lastPathComponent] %@ 源代码文件的名称。 
[NSThread callStackSymbols] %@ 程序员可读字符串的当前的堆栈跟踪的的NSArray。仅可用于调试,不要呈现给最终用户或在你的程序中做任何逻辑。

例子1:

NSLog( @"calling: %s", __PRETTY_FUNCTION__ );

输出:

calling : -[MyObjectClassName pressButton:]

例子2:

NSLog( @"%@", [NSThread callStackSymbols] );

输出:

2014-04-30 18:44:30.075 AVCustomEdit[52779:60b] (
 0  AVCustomEdit      0x0000efa6 -[APLSimpleEditor buildCompositionObjectsForPlayback:] + 278
 1  AVCustomEdit      0x0000686e -[APLViewController viewDidAppear:] + 590
 2  UIKit             0x007a4099 -[UIViewController _setViewAppearState:isAnimating:] + 526
 3  UIKit             0x007a4617 -[UIViewController __viewDidAppear:] + 146
 4  UIKit             0x007a49aa -[UIViewController _executeAfterAppearanceBlock] + 63
 5  UIKit             0x0069f0d0 ___afterCACommitHandler_block_invoke_2 + 33
 6  UIKit             0x0069f055 _applyBlockToCFArrayCopiedToStack + 403
 7  UIKit             0x0069ee9a _afterCACommitHandler + 568
 8  CoreFoundation    0x029db2bf __CFRunLoopDoObservers + 399
 9  CoreFoundation    0x029b9254 __CFRunLoopRun + 1076
 10 CoreFoundation    0x029b89d3 CFRunLoopRunSpecific + 467
 11 CoreFoundation    0x029b87eb CFRunLoopRunInMode + 123
 12 GraphicsServices  0x0318b5ee GSEventRunModal + 192
 13 GraphicsServices  0x0318b42b GSEventRun + 104
 14 UIKit             0x00681f9b UIApplicationMain + 1225
 15 AVCustomEdit      0x000026bd main + 141
 16 libdyld.dylib     0x0269e701 start + 1
)


使用DEBUG

因为NSLog会消耗资源,所以,我们需要在发布程序后,把NSLog注释掉。

初阶技巧:

在项目的设置中,有一个被预定义的DEBUG。只有在调试时,它才被赋值为1。所以,我们可以通过它来实现仅在 Debug 模式下编译的 NSLog。

#if DEBUG
NSLog( @"preparing to press button!" );
#endif
输出:
preparing to press button!

高级技巧

可以在pch文件中添加下面的代码来实现只在调试时才进行输出。

#ifdef DEBUG

#define NSLog(...) NSLog( __VA_ARGS__ )

#else

#define NSLog(...) {}

#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章