gpt4 book ai didi

swift3 - 如何将字典写入文件?

转载 作者:行者123 更新时间:2023-12-01 16:28:40 24 4
gpt4 key购买 nike

我有一个 FileHelper 类,我在其中实现了 3 个方法,它们的工作是将字典内容写入文件。这些方法是:

func storeDictionary(_ dictionary: Dictionary<String, String>, inFile fileName: String, atDirectory directory: String) -> Bool {
let ext = "txt"
let filePath = createFile(fileName, withExtension: ext, atDirectory: directory)
/**** //If I use this method, file is created and dictionary is saved
guard (dictionary as NSDictionary).write(to: filePath!, atomically: true) else {
return false
}
*/
guard NSKeyedArchiver.archiveRootObject(dictionary, toFile: (filePath?.absoluteString)!) else {
return false
}
return true
}
func createFile(_ file: String, withExtension ext: String, atDirectory directory: String) -> URL? {
let directoryPath = createDirectory(directory)
let filePath = directoryPath?.appendingPathComponent(file).appendingPathExtension(ext)

if !FileManager.default.fileExists(atPath: (filePath?.absoluteString)!) {
let success = FileManager.default.createFile(atPath: (filePath?.absoluteString)!, contents: nil, attributes: nil)
print("\(success)") //** here is the issue I investigated. Always prints false.
}

return filePath
}
func createDirectory(_ directory: String) -> URL? {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryPath = documentsDirectory.appendingPathComponent(directory)

do {
try FileManager.default.createDirectory(at: directoryPath, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
fatalError("Error creating directory: \(error.localizedDescription)")
}
return directoryPath
}

当我调用 FileHelper().storeDictionary(aValidDictionary, inFile: "abc", atDirectory: "XYZ") 来编写字典时,此过程失败。但是如果我使用

guard (dictionary as NSDictionary).write(to: filePath!, atomically: true) else {
return false
}

它有效。

NSKeyedArchiver.archiveRootObject(_:toFile:) 方法有什么问题??

为什么 FileManager.default.createFile(atPath: (filePath?.absoluteString)!, contents: nil, attributes: nil) 总是返回 false?

最佳答案

首先 filePath?.absoluteString 返回包括 file:// 方案的整个字符串(甚至转义百分比),并且该方法需要一个没有该方案的路径( filePath?.path - 命名有点困惑 ;-) ).

我建议将 [String:String] 字典保存为属性列表文件。无需显式创建文件。

我在 Swift-3-way 中稍微更改了方法的签名。此外,无需使用任何可选类型。

func store(dictionary: Dictionary<String, String>, in fileName: String, at directory: String) -> Bool {
let fileExtension = "plist"
let directoryURL = create(directory:directory)
do {
let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
try data.write(to: directoryURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension))
return true
} catch {
print(error)
return false
}
}

func create(directory: String) -> URL {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryURL = documentsDirectory.appendingPathComponent(directory)

do {
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
fatalError("Error creating directory: \(error.localizedDescription)")
}
return directoryURL
}

PS:你可以让 store 方法 can throw 并在调用方法中处理错误,而不是返回 Bool:

func store(dictionary: Dictionary<String, String>, in fileName: String, at directory: String) throws {
let fileExtension = "plist"
let directoryURL = create(directory:directory)

let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
try data.write(to: directoryURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension))
}

关于swift3 - 如何将字典写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42804845/

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