//不论是创建还是写入只需调用此段代码即可 如果文件未创建 会进行创建操作 - (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]; } }); }