//不管是建立仍是寫入只需調用此段代碼便可 若是文件未建立 會進行建立操做 - (void)writeToFileWithTxt:(NSString *)string{ dispatch_async(dispatch_get_global_queue(0, 0), ^{ @synchronized (self) { //獲取沙盒路徑 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); //獲取文件路徑 NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"testLogs2.text"]; //建立文件管理器 NSFileManager *fileManager = [NSFileManager defaultManager]; //若是文件不存在 建立文件 if(![fileManager fileExistsAtPath:theFilePath]){ NSString *str = @"日誌開始記錄\n"; [str writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; } NSLog(@"所寫內容=%@",string); NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath]; [fileHandle seekToEndOfFile]; //將節點跳到文件的末尾 NSData* stringData = [[NSString stringWithFormat:@"%@\n",string] dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:stringData]; //追加寫入數據 [fileHandle closeFile]; } }); }