為了列印日誌,可使用Objective-C編程語言中的NSLog
方法,首先在HelloWorld
示例中使用了這個方法。
下麵來看一下列印“Hello World”字樣的簡單代碼 -
#import <Foundation/Foundation.h>
int main() {
NSLog(@"Hello, World! \n");
return 0;
}
現在,當編譯並運行程式時,將得到以下結果 -
2018-11-15 09:53:09.761 main[22707] Hello, World!
在即時應用程式中禁用日誌
由於在應用程式中經常使用NSLog
,它將日誌資訊列印在設備的日誌中,並且在即時構建中列印日誌是不好的。 因此,使用類型定義來列印日誌,如下所示。
#import <Foundation/Foundation.h>
#define DEBUG 1
#if DEBUG == 0
#define DebugLog(...)
#elif DEBUG == 1
#define DebugLog(...) NSLog(__VA_ARGS__)
#endif
int main() {
DebugLog(@"Debug log, our custom addition gets \
printed during debug only" );
NSLog(@"NSLog gets printed always" );
return 0;
}
執行上面示例代碼,得到以下結果:
2018-11-15 09:50:28.903 main[11115] Debug log, our custom addition gets printed during debug only
2018-11-15 09:50:28.903 main[11115] NSLog gets printed always
現在,當在發佈模式下編譯並運行程式時,將得到以下結果 -
2018-11-15 09:50:28.903 main[11115] NSLog gets printed always
上一篇:
Objective-C類型轉換
下一篇:
Objective-C錯誤處理