【问题标题】:swift - save plist dictionary without overwriting keysswift - 保存 plist 字典而不覆盖键
【发布时间】:2015-09-17 15:34:46
【问题描述】:

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

    }

【问题讨论】:

    标签: ios swift dictionary


    【解决方案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)
    
    }
    

    【讨论】:

    • 谢谢,密钥总是以不同的值保存。 nameSave.text 是一个 UITextField,用户在其中选择要保存的键的值
    • @SNos 请查看我更新的帖子。在继续追加新数据之前,请确保在字典中填充您已经保存的数据。
    • 谢谢@Abhinav,我知道我需要加载旧值并在保存之前附加新值。但我不知道如何解决这个问题。请使用我的加载功能查看我的更新帖子
    • 我刚刚更新了我的答案。请检查一下。 @SNos
    • NSDictionary 没有成员 maned 'setObject' & 使用未解析的标识符 'dict'
    【解决方案2】:

    供将来参考,解决方案是:

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

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2017-07-22
      • 1970-01-01
      • 2011-01-08
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多