在AppDelegate.m的** application: didFinishLaunchingWithOptions**中:
#if (DEBUG == 1 || TARGET_OS_SIMULATOR)
#else
#ifdef FILELOG_SUPPORT
[self redirectNSlogToDocumentFolder];
#endif
#endif```
// 將NSlog打印信息保存到Document目錄下的文件中
- (void)redirectNSlogToDocumentFolder
{
//document文件夾
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
//
NSString *foldPath = [documentDirectory stringByAppendingFormat:@"/appLog"];
//文件保護等級
NSDictionary *attribute = [NSDictionary dictionaryWithObject:NSFileProtectionNone
forKey:NSFileProtectionKey];
[[NSFileManager defaultManager] createDirectoryAtPath:foldPath withIntermediateDirectories:YES attributes:attribute error:nil];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //每次啟動后都保存一個新的日志文件中
NSString *dateStr = [formatter stringFromDate:[NSDate date]];
NSString *logFilePath = [foldPath stringByAppendingFormat:@"/%@.log",dateStr];
[Utils checkFlieProtection:logFilePath];
// 將log輸入到文件
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}
pragma mark -File Handel
- (void)checkFlieProtection:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathSqlite = path;
NSDictionary *attributeSql = [fileManager attributesOfItemAtPath:pathSqlite error:nil];
if ([[attributeSql objectForKey:NSFileProtectionKey] isEqualToString:NSFileProtectionComplete]) {
NSDictionary *attribute = [NSDictionary dictionaryWithObject:NSFileProtectionCompleteUntilFirstUserAuthentication
forKey:NSFileProtectionKey];
[fileManager setAttributes:attribute ofItemAtPath:pathSqlite error:nil];
NSLog(@"改變文件權限 %@ : %@",path,attribute);
}
}
### Tips
- 文件保護等級屬性列表
NSFileProtectionNone //文件未受保護,隨時可以訪問 (Default)
NSFileProtectionComplete //文件受到保護,而且只有在設備未被鎖定時才可訪問
NSFileProtectionCompleteUntilFirstUserAuthentication //文件收到保護,直到設備啟動且用戶第一次輸入密碼
NSFileProtectionCompleteUnlessOpen //文件受到保護,而且只有在設備未被鎖定時才可打開,不過即便在設備被鎖定時,已經(jīng)打開的文件還是可以繼續(xù)使用和寫入
- freopen
[freopen()函數(shù)](http://c.biancheng.net/cpp/html/2508.html)用于文件流的的重定向,一般是將 stdin、stdout 和 stderr 重定向到文件。
所謂重定向,就是改變文件流的源頭或目的地。stdout(標準輸出流)的目的地是顯示器,printf()是將流中的內(nèi)容輸出到顯示器;可以通過freopen()將stdout 的目的地改為一個文件(如output.txt),再調(diào)用 printf(),就會將內(nèi)容輸出到這個文件里面,而不是顯示器。 freopen()函數(shù)的原型為: FILE *freopen(char *filename, char *type, FILE *stream);