我是 Swift 新手,正在尝试将字符串附加到 iOS 应用程序中的文本文件。
string.write
足够简单,但会覆盖现有信息。
write(toFile: atomically:encoding:)
也会覆盖现有信息,尽管文档指出它可能在将来扩展以允许添加信息。
使用 FileHandle 似乎合乎逻辑,但写入文件的方法(例如
init(forWritingTo:)
)需要 write(_:)
,而该函数是
已弃用!该文档不建议替代或替代。
let fileName: String = "mytextfile.txt"
let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let newFileUrl = directoryURL!.appendingPathComponent(fileName)
let textToAdd = "Help me, Obiwan!"
if let fileUpdater = try? FileHandle(forUpdating: newFileUrl) {
fileUpdater.seekToEndOfFile()
fileUpdater.write(textToAdd.data(using: .utf8)!)
fileUpdater.closeFile()
}
既然
write(_:)
已被弃用,我该如何执行此操作?
write(_:)
方法已弃用,文档现在建议替代方案:
来处理向文件句柄写入数据时的错误。write(contentsOf:)
因此,将
handle.write(_:)
替换为 try handle.write(contentsOf:)
。
也许:
func append(_ text: String, to filename: String) throws {
let data = Data(text.utf8)
let fileUrl = URL.applicationSupportDirectory // or `documentsDirectory` if you really want it to be a user-facing file
.appending(path: filename)
do {
let handle = try FileHandle(forUpdating: fileUrl)
defer { handle.closeFile() }
handle.seekToEndOfFile()
try handle.write(contentsOf: data)
} catch CocoaError.fileNoSuchFile {
try data.write(to: fileUrl)
} catch {
throw error
}
}
他们的想法是,他们已经弃用了
write(_:)
函数,而使用了能够抛出错误的函数。