gpt4 book ai didi

ios - filemanager.createFileAtPath 工作不正常

转载 作者:行者123 更新时间:2023-11-29 01:16:30 24 4
gpt4 key购买 nike

我尝试使用 NSFileManager 和方法 createFileAtPath 创建一个 PLIST 文件。最后,文件被创建,它的大小为 0 字节,我什至可以在 Finder 中看到该文件的特定 PLIST-Icon。但是当我想打开它时(例如使用 Xcode)它说:The data couldn't be read because it isn't in the correct format。我想写入此文件,但当它的格式不正确时,我无法执行此操作。

文件创建有问题,但我不知道是什么。我希望你能帮我解决这个问题。这是我的代码:

pListPath = NSURL(fileURLWithPath: reportsPath.path!).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

let data: NSData = NSData()
var isDir: ObjCBool = false

if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)
{
print("File already exits")
}
else
{
let success = fileManager.createFileAtPath(pListPath.path!, contents: data, attributes: nil)

print("Was file created?: \(success)")
print("plistPath: \(pListPath)")
}

reports.path = .../UserDir/.../Documents/Reports

非常感谢任何帮助。

最佳答案

filemanager.createFileAtPath 绝对正确,
但是您通过将一个空的 NSData 对象写入磁盘来创建一个空文件。
NSData 对象不会隐式序列化为属性列表。

要么使用 NSPropertyListSerialization 类,要么——更简单——将一个空字典写入磁盘。

let dictionary = NSDictionary()
let success = dictionary.writeToURL(pListPath, atomically: true)
print("Was file created?: \(success)")
print("plistPath: \(pListPath)")

PS:您不需要从 URL 创建 URL

pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)

但我建议使用更具描述性的变量名称来区分 String 路径和 NSURL 例如pListURLreportsURL

关于ios - filemanager.createFileAtPath 工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35119124/

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