Chinaunix首页 | 论坛 | 博客
  • 博客访问: 127160
  • 博文数量: 24
  • 博客积分: 825
  • 博客等级: 准尉
  • 技术积分: 280
  • 用 户 组: 普通用户
  • 注册时间: 2004-11-02 09:09
个人简介

打不死的蟑螂

文章分类

全部博文(24)

文章存档

2017年(1)

2016年(2)

2014年(1)

2013年(3)

2012年(1)

2011年(1)

2010年(1)

2009年(1)

2008年(3)

2006年(1)

2005年(7)

2004年(2)

我的朋友

分类: iOS平台

2013-11-15 09:12:34

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.

Table 1  Preprocessor 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 2  Expressions 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.

阅读(513) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~