[英]filemanager.createFileAtPath works not correctly
我尝试使用NSFileManager
和方法createFileAtPath
创建一个PLIST-File。 最后,创建了文件,文件大小为0字节,我什至可以在Finder中看到该文件的特定PLIST图标。 但是,当我想打开它(例如使用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)")
}
report.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
例如pListURL
和reportsURL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.