我正在創建一個筆記應用程序,我試圖將數據保存到plist字典中,但是,當我保存新筆記的代碼將替換舊筆記時。swift - 保存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")
}
}
謝謝你,關鍵的常是保存不同的值。 nameSave.text是一個UITextField,用戶爲要保存的鍵選擇一個值 – SNos
好的。那麼第一點呢,你檢查了嗎? – Abhinav
不知道在哪裏以及如何放置斷點 – SNos