将字典写入文件

时间:2015-11-24 16:05:31

标签: dictionary swift2 nsdictionary plist

从plist文件中读取[String:String]类型的字典。然后我添加一个新的键值对 - 在进入后台模式时,我使用以下代码将其写入相同的路径:

func saveToFile () {
    let mo_tmp: NSDictionary = ortdict as NSDictionary
    mo_tmp.writeToFile(fileat, atomically: true)
    print("mo_tmp:", mo_tmp)
    print("fileat:", fileat)
}

重新启动程序时,会再次读入同一文件。但是,我添加到字典中的条目(并在上面的打印输出中显示)无处可去。在模拟器或真正的iPhone 5上运行测试时会发生这种情况。

1 个答案:

答案 0 :(得分:0)

检查writeToFile()的返回值以查看它是否为真。如果不是,则字典无法写入文件,因为并非所有包含的对象都是属性列表对象。

请参阅https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/#//apple_ref/occ/instm/NSDictionary/writeToFile:atomically