2016-01-31 88 views
0

我尝试使用NSFileManager和方法createFileAtPath创建一个PLIST文件。最后,该文件已创建,它的大小为0字节,我甚至可以在Finder中看到该文件的特定PLIST图标。 但是,当我想打开它(例如与Xcode)它说:The data couldn't be read because it isn't in the correct format。 我想写入这个文件,但是当它不是正确的格式,我不能这样做。filemanager.createFileAtPath工作不正确

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

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

任何帮助,高度赞赏。

+0

在iOS中,您始终必须使用NSURL或NSFileManager创建对文档文件夹的引用。是你做的吗? – vadian

+0

我创建了这样的参考。我从另一个帖子复制它在这里:'let rootPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).first' – user1895268

回答

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

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

创建一个URL,但我建议使用更具描述性的变量名称分辨String路径和NSURL例如pListURLreportsURL

+0

非常感谢,它的工作原理 – user1895268