Swift 2.2。将字典保存到plist

时间:2016-06-02 10:00:33

标签: ios dictionary swift2.2

我有这两个功能。首先,readPlaylist()似乎工作正常。如果plist已经保存在DocumentDirectory中,它将从那里返回,否则它将被复制到路径然后返回。

函数savePlaylist(dict:NSMutableDictionary)接受一个NSMutableDictionary并将其打印出来。此函数使用与readPlaylist()相同的路径代码,因此路径应该是正确的。 然后我尝试将dict写入url。我没有错误,但writeToUrl返回false,当我打印出resultDictionary时,我将原始plist复制到DocumentDirectory,没有进行任何更改。

我也尝试了“旧方式”并使用了writeToFile,但结果相同。

dict包含字符串键,其中包含保存自定义对象的数组值

为什么我不能将我的字典保存到plist?

代码:

 func readPlaylist() -> NSMutableDictionary  {

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
    let path = NSURL(fileURLWithPath: paths as String).URLByAppendingPathComponent("Playlists.plist")


    let fileManager = NSFileManager.defaultManager()

    //check if file exists
    if !fileManager.fileExistsAtPath(path.path!){
        let plistPathInBundle = NSBundle.mainBundle().pathForResource("Playlists", ofType: "plist") as String!
        do {
            try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: path.path!)
        }catch{
            print("Error occurred while copying file to document \(error)")
        }
    } else {
        print("Playlists.plist already exits at path.")
    }
    let resultDictionary = NSMutableDictionary(contentsOfURL: path)
    print("Loaded Playlists.plist file is --> \(resultDictionary?.description)")

    return resultDictionary!

}

func savePlaylist(dict: NSMutableDictionary) {

    print("mydict --> \(dict.description)")

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
    let path = NSURL(fileURLWithPath: paths as String).URLByAppendingPathComponent("Playlists.plist")

    print("test if true or false: \(dict.writeToURL(path, atomically: true))")

    dict.writeToURL(path, atomically: true)


    let resultDictionary = NSMutableDictionary(contentsOfURL: path)
    print("Saved Playlists.plist file is --> \(resultDictionary?.description)")

}    

Playlist.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>QuePlayer</key>
    <array/>
</dict>
</plist>

0 个答案:

没有答案
相关问题