在Xcode中重新定义NSLog

Pix*_*man 2 objective-c nslog

我对Xcode和Objective-C有疑问.

我想在Xcode中做这个简单的动作:

如果我输入:

NSLog(@"something else");
Run Code Online (Sandbox Code Playgroud)

我希望Xcode编写(或在编译后执行):

NSLog(@"[%@] something else", NSStringFromClass([self class]));
Run Code Online (Sandbox Code Playgroud)

另一种方法可能是Xcode 4在自动完成菜单中提示,当我键入NSLog时...

Pas*_*cal 7

这是一套完整的Log #define指令(包括ULog,一种基于UIAlertView的Logging功能)

// DLog will output like NSLog only when the DEBUG variable is set

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

// ALog will always output like NSLog

#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

// ULog will show the UIAlertView only when the DEBUG variable is set 

#ifdef DEBUG
#   define ULog(fmt, ...)  { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__]  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#else
#   define ULog(...)
#endif
Run Code Online (Sandbox Code Playgroud)

正如Ciryon所写,只需将它们放在预编译头(.pch)文件中即可.

(来源:http://overbythere.co.uk/blog/2012/01/alternatives-nslog)