簡體   English   中英

swift - 保存plist字典而不覆蓋鍵

[英]swift - save plist dictionary without overwriting keys

我正在創建一個筆記應用程序,我正在嘗試將數據保存到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")
        }

    }

在此輸入圖像描述

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

}

為了將來參考,解決方案是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM