在 Swift 中将字符串附加到文本文件的最佳方法

问题描述 投票:0回答:1

我是 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(_:) 已被弃用,那么推荐的方法是什么?

swift
1个回答
0
投票

write(_:)
已弃用,正如 文档 所说:

使用

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(_:)
函数,而使用了能够抛出错误的函数。

© www.soinside.com 2019 - 2024. All rights reserved.