我需要在.txt文件中寫入一些日誌,爲了更清晰起見,我想讓某些文本着色。是否可以在文件中寫入彩色文本?
我該怎麼辦這個把戲?
這裏我的功能
+(void)writeInLogFile:(NSString *)strLog inFolder:(NSString *)folder fileName:(NSString *)fileName extension:(NSString *)extension
{
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL LogFileOnIpad = [[NSUserDefaults standardUserDefaults] boolForKey:PREF_LOG_FILE_ON_IPAD];
if(LogFileOnIpad)
{
//Create Directory
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:folder];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) //Does directory already exists?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(@"Create directory error: %@", error);
}
}
NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@",path,fileName,extension];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[strLog dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
}
這是我用我的功能:
NSString* str = @"SOME STRING TO WRITE IN LOG FILE";
[HandleString writeInLogFile:str inFolder:LOGS_FOLDER fileName:[NSString stringWithFormat:@"%@_%@",LOGS_IPAD,[HandleString convertDayDateForLog]] extension:@"txt"];
我想聲明的標籤用的UIColor和文字傳遞給我的功能,但沒有成功。
不是真的重複,但:http://stackoverflow.com/q/8235532/620197 –