Swift - 保存Plist字典而不覆盖键

3

我正在创建一个笔记应用程序,尝试将数据保存到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个回答

1
要点1:请在从文件系统加载字典后设置断点并仔细检查,它是否包含之前保存的数据。这很可能是正确的,然后第2点将帮助您。如果此点出现问题,请确保修复它,您就能解决它:)。 要点2:字典必须具有唯一的键。问题在于您下面的语句。确保每次保存新笔记时,都使用新键保存。在保存数据到字典时,请检查nameSave.text值。
dict[nameSave.text] = noteResult.text

编辑:

我看到问题在于您没有使用文件系统中已保存的notes.plist初始化字典。您必须首先确保将字典填充到文件系统中的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)

}

谢谢,该密钥始终以不同的值保存。nameSave.text是一个UITextField,用户选择要保存的密钥值。 - SNos
NSDictionary没有名为'setObject'的成员 & 使用了未解决的标识符'dict'。 - SNos
我假设你将字典声明为变量。请检查我在这行代码上的更新。 - Abhinav
我已经将“var”更改为“let”,但仍然出现相同的错误。请参见附加的图片。 - SNos
我认为你没有看过我的更新。我希望你将语法更改为dict[nameSave.text] = noteResult.text - Abhinav
显示剩余3条评论

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)")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接