【问题标题】:filemanager.createFileAtPath works not correctlyfilemanager.createFileAtPath 工作不正常
【发布时间】:2023-04-10 20:31:16
【问题描述】:

我尝试使用NSFileManagercreateFileAtPath 方法创建一个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

非常感谢任何帮助。

【问题讨论】:

  • 在 iOS 中,您始终必须使用 NSURLNSFileManager 创建对文件夹 Documents 的引用。你这样做了吗?
  • 我创建了这样的参考。我从这里的另一个帖子中复制了它:let rootPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first

标签: ios nsurl nsfilemanager


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 2015-01-16
    • 1970-01-01
    • 2016-08-02
    • 2020-02-18
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多