swift - 保存plist字典而不覆盖键

时间:2015-09-17 15:34:47

标签: ios swift dictionary

我正在创建一个笔记应用程序,我正在尝试将数据保存到plist字典中,但是,当我保存新笔记时,我所拥有的代码将替换旧笔记。

如何在不更换旧数据的情况下在字典中添加新数据?

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
            let documentsDirectory = paths.objectAtIndex(0) as! NSString
            let path = documentsDirectory.stringByAppendingPathComponent("notes.plist")
            var dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
            //saving

            dict.setObject(noteResult.text, forKey: nameSave.text)

            //writing

            dict.writeToFile(path, atomically: false)
            let resultDictionary = NSMutableDictionary(contentsOfFile: path)
            println("Saved note.plist file is --> \(resultDictionary?.description)")

加载说明:

func loadNotes(){

        let plistPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
        let DocumentsDirectory = plistPath[0] as! String
        let path = DocumentsDirectory.stringByAppendingPathComponent("notes.plist")
        let fileManager = NSFileManager.defaultManager()

        if (!fileManager.fileExistsAtPath(path)) {

            if let bundlePath = NSBundle.mainBundle().pathForResource("notes", ofType: "plist") {

                let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
                println("Bundle notes.plist file is --> \(resultDictionary?.description)")
                fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
                println("copy")

            } else {
                println("notes.plist not found")
            }


        }else {
            println("note.plist already exists")

            //fileManager.removeItemAtPath(path, error: nil)
        }

        let resultDictionary = NSMutableDictionary(contentsOfFile: path)
        println("Loaded notes.plist file is --> \(resultDictionary?.description)")
        var myDict = NSDictionary(contentsOfFile: path)

        if let dict = myDict {
            //load values

        } else {

            println("worning ccould not create dictionary from notes.plist, default values will be used")
        }

    }

enter image description here

2 个答案:

答案 0 :(得分:1)

第1点:您可以在从文件系统加载字典后设置断点并仔细检查,它包含先前保存的数据。这很可能是真的,然后第2点会对你有所帮助。如果这一点破裂那么请确保解决这个问题,你将破解它:)。

第2点:字典必然具有唯一键。问题出在你的声明中。确保每次保存新笔记时,都会使用新密钥保存。检查一下 每当您在字典中保存数据时,都会生成nameSave.text值。

dict[nameSave.text] = noteResult.text

修改

我在这里看到的问题是你没有用文件系统中已保存的文件初始化你的字典。您必须首先确保使用文件系统中的 notes.plist 填充字典,然后将新数据附加到其中,最后将其保存回来。

这就是我要这样做的方式;只是在流程中结合了两种提到的方法。在保存操作的触发器上调用此函数。在这里,我认为,第一次检查可能会丢失。我没有测试这段代码所以请耐心等待。

func saveNotes() {
    // First fetch old notes
    let plistPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let DocumentsDirectory = plistPath[0] as! String
    let path = DocumentsDirectory.stringByAppendingPathComponent("notes.plist")
    let fileManager = NSFileManager.defaultManager()

    if (!fileManager.fileExistsAtPath(path)) {

        if let bundlePath = NSBundle.mainBundle().pathForResource("notes", ofType: "plist") {

            let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
            println("Bundle notes.plist file is --> \(resultDictionary?.description)")
            fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
            println("copy")

        } else {
            println("notes.plist not found")
        }


    } else {
        println("note.plist already exists")

        //fileManager.removeItemAtPath(path, error: nil)
    }

    let resultDictionary = NSMutableDictionary(contentsOfFile: path)
    println("Loaded notes.plist file is --> \(resultDictionary?.description)")
    var myDict = NSDictionary(contentsOfFile: path)

    if let dict = myDict {
        // Save new value
        dict.setObject(noteResult.text, forKey: nameSave.text)
    } else {
        println("worning ccould not create dictionary from notes.plist, default values will be used")
    }

    // Now save it back
    dict.writeToFile(path, atomically: false)

}

答案 1 :(得分:0)

为了将来参考,解决方案是:

// First fetch old notes
            let plistPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
            let DocumentsDirectory = plistPath[0] as! String
            let path = DocumentsDirectory.stringByAppendingPathComponent("notes.plist")
            let fileManager = NSFileManager.defaultManager()

            if (!fileManager.fileExistsAtPath(path)) {

                if let bundlePath = NSBundle.mainBundle().pathForResource("notes", ofType: "plist") {

                    let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
                    println("Bundle notes.plist file is --> \(resultDictionary?.description)")
                    fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
                    println("copy")

                } else {
                    println("notes.plist not found")
                }


            } else {
                println("note.plist already exists")

                //fileManager.removeItemAtPath(path, error: nil)
            }

            var myDict = NSDictionary(contentsOfFile: path)

            if let dict = myDict {
                // Save new value
                var noteResultAll = "Date: " + saveDate.text! + "\n" + noteResult.text

                dict.setValue(noteResultAll, forKey: nameSave.text)
                dict.writeToFile(path, atomically: false)
            } else {
                println("worning ccould not create dictionary from notes.plist, default values will be used")
            }

            // Now save it back

            let resultDictionary = NSMutableDictionary(contentsOfFile: path)
            println("Loaded notes.plist file is --> \(resultDictionary?.description)")