这可以使用问题导航器来完成。我写了一篇博客文章深入讨论了这个问题:
http://finalize.com/2014/10/20/logging-and-bookmarks-with-objective-c-and-swift/
以下是文章的关键部分。
Objective-C 临时日志记录和 FIXME 标记
将以下内容添加到通用头文件中:
#define DO_PRAGMA(x) _Pragma (#x)
#define FIXME(x) DO_PRAGMA(message (STR(__LINE__) " FIXME: " #x))
#define CLOG(x) NSLog(@#x); DO_PRAGMA(message (STR(__LINE__) " NSLog: " #x))
// If ENABLE_PRAGMA_FOR_FLOG is set, FLOG and NLOG both use pragma.
// If not set, only NLOG uses pragma.
#if ENABLE_PRAGMA_FOR_FLOG
#define FLOG(LogType, MacroType, FormatLiteral, ...) NSLog (@"%s(%u): " LogType " \n" FormatLiteral "\n\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); DO_PRAGMA(message (STR(__LINE__) " " MacroType ": " FormatLiteral " " #__VA_ARGS__))
#define NLOG(FormatLiteral, ...) FLOG("","NSLog", FormatLiteral, ##__VA_ARGS__)
#else
#define FLOG(LogType, MacroType, FormatLiteral, ...) NSLog (@"%s(%u): " LogType " \n" FormatLiteral "\n\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);
#define NLOG(FormatLiteral, ...) FLOG("","NSLog", FormatLiteral, ##__VA_ARGS__) DO_PRAGMA(message (STR(__LINE__) " NSLog : " FormatLiteral " " #__VA_ARGS__))
#endif
以上代码利用了 Diagnostics Pragmas (https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html) 和可变参数宏(宏采用可变数量的 args)
您可以使用以下示例中的宏:
FIXME(Need to fix this bug in the next iteration)
CLOG(A simple constant string log message)
NSString *msg = @"My message";
NLOG("msg = %@",msg)
请注意,FIXME 和 CLOG 宏实例不需要引号。 NLOG 宏不需要 @ 字符串前缀,但使用引号。没有一个宏需要尾随分号。
Objective-C 永久日志记录
如果您想使用宏进行永久记录而不显示在问题导航器中,您可以创建一个项目特定的宏,如下所示。注意我们是如何在 FLOG() 调用之后去掉 DO_PRAGMA() 的:
#define PLOG_CORE_DATA(FormatLiteral, ...) FLOG("PLOG_CORE_DATA","PLOG_CORE_DATA", FormatLiteral, ##__VA_ARGS__)
这将提供 NLOG 的强大功能,可以将函数和行号添加到您的日志输出中,如果您愿意,还可以启用宏在问题导航器中显示(请参阅下一节)。
更多关于 FLOG
要在问题导航器中显示所有日志记录宏(即 NLOG 和项目特定版本),请在上述任何标头代码之前设置 ENABLE_PRAGMA_FOR_FLOG:
#define ENABLE_PRAGMA_FOR_FLOG 1
你会注意到 FLOG 有两个参数,分别是 LogType 和 MacroType。第一个允许项目特定的宏向控制台输出添加前缀。当 ENABLE_PRAGMA_FOR_FLOG 设置为 1 时使用第二个,以允许项目特定的宏为问题导航器指定标签。
Swift 临时日志记录和 FIXME 标记
Swift 不使用预处理器,因此不能选择编译指示标志和宏。
尽管通过使用良性警告“将强制向下转换为可选将永远不会产生'nil'”,仍然可以提供与 Objective-C 使用的 NLOG 和 FIXME 宏类似的功能
我创建了一些代码来执行此操作,在 MIT 许可下可用:
https://github.com/scottcarter/SNLog
以下是 SNLog 文档中的用法示例:
// Add a FIXME marker to Issue Navigator
g_fixme = g_anyFixme as SNLog.Fixme
// Log to console and add to Issue Navigator
g_log = SNLog.info("<message>") as SNLog
// Only log to console, but still add function and line number to output.
SNLog.info("<message>")
SNLog GitHub 页面上展示了更多使用案例。
关于生成警告的原因以及 SNLog 如何工作的详细信息,请参阅博客文章 http://finalize.com/2014/10/20/logging-and-bookmarks-with-objective-c-and-swift/