Swift 3:不能将数据写入plist文件

我正在尝试使用名为Data.plist的文件来存储一些简单的非结构化数据,并将该文件放在我的应用程序的根文件夹中。 为了简化对这个文件的读写,我创build了下面的DataManager结构体。 它可以读取没有问题的Data.plist文件,但不能将数据写入文件。 我不确定问题出在哪里,有谁能find可能出错的地方?

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