對於真機,日誌沒法保存,不好分析問題。所以有必要將日誌保存到應用的Docunment目錄下,並設置成共享文件,這樣才能取出分析。
首先是日誌輸出,分爲c的printf和標準的NSLog輸出,printf會向標準輸出(sedout)打印,而NSLog則是向標準出錯(stderr),我們需要同時讓他們都將日誌打印到一個文件中。
例子:
freopen("xx.log","a+",stdout);
freopen("xx.log","a+",stderr);
具體做法:
// 將NSlog打印信息保存到Document目錄下的文件中
- (void)redirectNSlogToDocumentFolder
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"dr.log"];// 注意不是NSData!
NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
// 先刪除已經存在的文件
NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager removeItemAtPath:logFilePath error:nil];
// 將log輸入到文件
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}
此函數要在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
中調用,這個函數在AppDelegate.m中實現的。
/*******************************************************************************/
// 當真機連接Mac調試的時候把這些註釋掉,否則log只會輸入到文件中,而不能從xcode的監視器中看到。
// 如果是真機就保存到Document目錄下的drm.log文件中
UIDevice *device = [UIDevice currentDevice];
if (![[device model] isEqualToString:@"iPad Simulator"]) {
// 開始保存日誌文件
[self redirectNSlogToDocumentFolder];
}
/*******************************************************************************/
最後配置共享文件夾:
在應用程序的Info.plist文件中添加UIFileSharingEnabled鍵,並將鍵值設置爲YES。將您希望共享的文件放在應用程序的Documents目錄。一旦設備插入到用戶計算機,iTunes 9.1就會在選中設備的Apps標籤中顯示一個File Sharing區域。此後,用戶就可以向該目錄添加文件或者將文件移動到桌面計算機中。如果應用程序支持文件共享,當文件添加到Documents目錄後,應用程序應該能夠識別並做出適當響應。例如說,應用程序可以將新文件的內容顯示界面上。請不要向用戶展現目錄的文件列表並詢問他們希望對文件執行什麼操作。
就是說,一旦設備連接上電腦,可以通過iTune查看指定應用程序的共享文件夾,將文件拷貝到你的電腦上看。
參考連接:
1.http://hi.baidu.com/ios_zb_com/item/ea528f4a8b1100d8c1a59217
2.http://www.cnblogs.com/ThankForYou/archive/2012/09/12/2681739.html
3.http://dingran.iteye.com/blog/1773573