我正在做一个关于在Xcode中调试的演示,想要获得更多关于有效使用NSLog的信息。
我特别想问两个问题:
是否有一种方法可以轻松地NSLog当前方法的名称/行号? 在编译发布代码之前,是否有一种方法可以轻松地“禁用”所有nslog ?
我正在做一个关于在Xcode中调试的演示,想要获得更多关于有效使用NSLog的信息。
我特别想问两个问题:
是否有一种方法可以轻松地NSLog当前方法的名称/行号? 在编译发布代码之前,是否有一种方法可以轻松地“禁用”所有nslog ?
当前回答
这是一个没有答案的新把戏。你可以用printf代替NSLog。这将给你一个干净的日志:
使用NSLog,你会得到这样的东西:
2011-11-03 13:43:55.632 myApp[3739:207] Hello Word
但是用printf你只能得到:
Hello World
使用这段代码
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...) {}
#endif
其他回答
更改现有nslog以显示调用它们的行号和类是很容易的。在前缀文件中添加一行代码:
#define NSLog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
这很简单,举个例子
-(void) applicationwillenter前台:(UIApplication *)application { NSLog(@“% s”,__PRETTY_FUNCTION__); }
输出: - - - - - - [AppDelegate applicationWillEnterForeground:]
在以上答案的基础上,以下是我抄袭并想出的答案。还添加了内存日志记录。
#import <mach/mach.h>
#ifdef DEBUG
# define DebugLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DebugLog(...)
#endif
#define AlwaysLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#ifdef DEBUG
# define AlertLog(fmt, ...) { \
UIAlertView *alert = [[UIAlertView alloc] \
initWithTitle : [NSString stringWithFormat:@"%s(Line: %d) ", __PRETTY_FUNCTION__, __LINE__]\
message : [NSString stringWithFormat : fmt, ##__VA_ARGS__]\
delegate : nil\
cancelButtonTitle : @"Ok"\
otherButtonTitles : nil];\
[alert show];\
}
#else
# define AlertLog(...)
#endif
#ifdef DEBUG
# define DPFLog NSLog(@"%s(%d)", __PRETTY_FUNCTION__, __LINE__);//Debug Pretty Function Log
#else
# define DPFLog
#endif
#ifdef DEBUG
# define MemoryLog {\
struct task_basic_info info;\
mach_msg_type_number_t size = sizeof(info);\
kern_return_t e = task_info(mach_task_self(),\
TASK_BASIC_INFO,\
(task_info_t)&info,\
&size);\
if(KERN_SUCCESS == e) {\
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; \
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \
DebugLog(@"%@ bytes", [formatter stringFromNumber:[NSNumber numberWithInteger:info.resident_size]]);\
} else {\
DebugLog(@"Error with task_info(): %s", mach_error_string(e));\
}\
}
#else
# define MemoryLog
#endif
这是一个没有答案的新把戏。你可以用printf代替NSLog。这将给你一个干净的日志:
使用NSLog,你会得到这样的东西:
2011-11-03 13:43:55.632 myApp[3739:207] Hello Word
但是用printf你只能得到:
Hello World
使用这段代码
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...) {}
#endif
新增的DLog。而不是完全删除调试从发布的应用程序,只是禁用它。当用户有问题需要调试时,只需告知如何在发布的应用程序中启用调试,并通过电子邮件请求日志数据。
简短版本:创建全局变量(是的,懒惰和简单的解决方案),并修改DLog如下所示:
BOOL myDebugEnabled = FALSE;
#define DLog(fmt, ...) if (myDebugEnabled) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
更长的答案在joromus iLessons iLearned:如何在发布的应用程序中进行动态调试日志记录