iPhone開發(fā)技巧之日志保存教程
iPhone開發(fā)技巧之日志保存教程是本文要介紹的內(nèi)容,大部分人調(diào)試程序都是看日志吧,這里我就給大家總結(jié)一下iphone程序中添加保存日志的方法。
Objective-C開發(fā)程序的時候,有專門的日志操作類NSLog,它將指定的輸出到標(biāo)準(zhǔn)的錯誤輸出上(stderr)。我們可以利用它在Xcode的日志輸出窗口,或者是輸出到具體的文件當(dāng)中。
下面是我在程序中常用到的日志宏,用DEBUG開關(guān)管理,也就是說只有在DEBUG模式下才讓日志輸出 :
- #ifdef DEBUG
- # define LOG(fmt, ...) do { \
- NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__]; \
- NSLog((@"%@(%d) " fmt), [file lastPathComponent], __LINE__, ##__VA_ARGS__); \
- [file release]; \
- } while(0)
- # define LOG_METHOD NSLog(@"%s", __func__)
- # define LOG_CMETHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd))
- # define COUNT(p) NSLog(@"%s(%d): count = %d\n", __func__, __LINE__, [p retainCount]);
- # define LOG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
- #else
- # define LOG(...)
- # define LOG_METHOD
- # define LOG_CMETHOD
- # define COUNT(p)
- # define LOG_TRACE(x)
- #endif
可以看到,除了標(biāo)準(zhǔn)的用戶定義輸出外,我還加入了許多有用的信息,比如源程序文件位置,行號,類名,函數(shù)名等。具體的應(yīng)用可以在具體的開發(fā)過程中添加、刪除。
真機(jī)測試的時候,可以利用freopen將標(biāo)準(zhǔn)錯誤輸出保存到指定的文件當(dāng)中,這樣就可以在問題發(fā)生后分析日志文件。
- - (void)redirectNSLogToDocumentFolder{
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
- NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
- freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
- }
- - (void)applicationDidFinishLaunching:(UIApplication *)application {
- // 真機(jī)測試時保存日志
- if ([CDeviceInfo getModelType] != SIMULATOR) {
- [self redirectNSLogToDocumentFolder];
- }
- .....
- }
小結(jié):iPhone開發(fā)技巧之日志保存教程的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!