我正在尝试创建一个文件并通过在每次点击“保存”按钮时添加一个字符串来更新文件。但是,每当我点击保存时,它会使用最新的字符串创建一个新文件(覆盖)。我的代码如下,我该如何解决?请帮忙!
func pathToDocsFolder() -> String {
let pathToDocumentsFolder =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
return pathToDocumentsFolder.stringByAppendingPathComponent("/log.csv")
}
@IBAction func saveSample(sender: AnyObject) {
let string = LabelText + ";" + SampleNoOne.text! + ";" + fromOne.text! + ";" + toOne.text! + ";" + casingBlowsOne.text! + ";"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(pathToDocsFolder()){
filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
}
let fileHandle = NSFileHandle.init(forUpdatingAtPath: pathToDocsFolder())
fileHandle!.seekToEndOfFile()
fileHandle!.writeData(data)
fileHandle!.closeFile()
答案 0 :(得分:0)
更新
if filemanager.fileExistsAtPath(pathToDocsFolder()){
filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
}
为:
if filemanager.fileExistsAtPath(pathToDocsFolder()) == false {
filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
}
答案 1 :(得分:0)
如果要在文件中追加使用“forWritingAtPath”而不是“forUpdatingAtPath” 替换以下行:
let fileHandle = NSFileHandle.init(forUpdatingAtPath: pathToDocsFolder())
用
let fileHandle = NSFileHandle.init(forWritingAtPath: pathToDocsFolder())
另外,请确保检查现有文件的条件是否正确。