gpt4 book ai didi

ios - swift 3 : cannot write data to plist file

转载 作者:行者123 更新时间:2023-11-29 00:26:58 32 4
gpt4 key购买 nike

我正在尝试使用一个名为 Data.plist 的文件来存储一些简单的非结构化数据,并将此文件放在我的应用程序的根文件夹中。为了简化对该文件的读/写,我创建了以下 DataManager 结构。它可以毫无问题地读取 Data.plist 文件,但无法将数据写入文件。我不确定问题出在哪里,任何人都可以发现哪里可能有问题吗?

struct DataManager {

static var shared = DataManager()

var dataFilePath: String? {
return Bundle.main.path(forResource: "Data", ofType: "plist")
}

var dict: NSMutableDictionary? {
guard let filePath = self.dataFilePath else { return nil }
return NSMutableDictionary(contentsOfFile: filePath)
}

let fileManager = FileManager.default

fileprivate init() {

guard let path = dataFilePath else { return }
guard fileManager.fileExists(atPath: path) else {
fileManager.createFile(atPath: path, contents: nil, attributes: nil) // create the file
print("created Data.plist file successfully")
return
}
}

func save(_ value: Any, for key: String) -> Bool {
guard let dict = dict else { return false }

dict.setObject(value, forKey: key as NSCopying)
dict.write(toFile: dataFilePath!, atomically: true)

// confirm
let resultDict = NSMutableDictionary(contentsOfFile: dataFilePath!)
print("saving, dict: \(resultDict)") // I can see this is working

return true
}

func delete(key: String) -> Bool {
guard let dict = dict else { return false }
dict.removeObject(forKey: key)
return true
}

func retrieve(for key: String) -> Any? {
guard let dict = dict else { return false }

return dict.object(forKey: key)
}
}

最佳答案

您不能修改应用程序包中的文件。因此,您使用 Bundle.main.path(forResource:ofType:) 获得的所有文件都是可读但不可写的。

如果您想修改此文件,您需要先将其复制到应用的文档目录中。

let initialFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "Data", ofType: "plist")!)
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
let writableFileURL = documentDirectoryURL.appendingPathComponent("Data.plist", isDirectory: false)

do {
try FileManager.default.copyItem(at: initialFileURL, to: writableFileURL)
} catch {
print("Copying file failed with error : \(error)")
}

// You can modify the file at writableFileURL

关于ios - swift 3 : cannot write data to plist file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42736244/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com