向字典添加值不会保留

时间:2016-05-18 17:19:23

标签: ios swift class dictionary persist

我正在尝试将值添加到LocalsInformation类中的locals字典中,但数据不会持久存在。我在print(localInformation)上设置了一个断点,我能够看到在字典中添加了一个新值,但是当我重新加载应用程序时,该值不会持续存在。我相信我可能只是更改本地词典的副本而不是实际值。

class LocalsInformation{
var locals: [String: Dictionary<String, String>] = ["Jerry":["City":Destination.Seattle.rawValue,"Preference": TravellingPreference.Adventurer.rawValue, "Gender": Gender.Male.rawValue],"Beth":["City":Destination.Seattle.rawValue,"Preference":TravellingPreference.Foodie.rawValue, "Gender": Gender.Female.rawValue]}

let localInput = [[Destination.Austin.rawValue, Destination.Boston.rawValue, Destination.Chicago.rawValue, Destination.NewYork.rawValue, Destination.SanFrancisco.rawValue, Destination.Seattle.rawValue],[TravellingPreference.Adventurer.rawValue, TravellingPreference.ArtDesignLover.rawValue, TravellingPreference.CulturalExplorer.rawValue, TravellingPreference.Foodie.rawValue, TravellingPreference.HistoryBuff.rawValue, TravellingPreference.NightOwl.rawValue]]


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    let citySelected = localInput[0][pickerView.selectedRowInComponent(0)]
    let preferenceSelected = localInput[1][pickerView.selectedRowInComponent(1)]
    if let name = nameTextField.text{
        var localInformation = LocalsInformation().locals
        localInformation[name] = [
            "City": citySelected,
            "Preference": preferenceSelected,
            "Gender": "Female"
        ]
        LocalsInformation().locals[name] = localInformation[name]
    print(localInformation)
    }

}

1 个答案:

答案 0 :(得分:1)

为什么信息会持续存在?字典在RAM中创建,一旦你重新加载应用程序,它们就会消失。要在磁盘上保留字典,您需要显式使用持久性机制。 iOS API提供了几个。一个易于使用的字典是JSON:

https://www.raywenderlich.com/120442/swift-json-tutorial

但您也可以使用自己的文件格式,NSUserDefaults等。