swift NSUserdefault项目未被删除

时间:2018-01-23 03:03:10

标签: swift dictionary nsuserdefaults

我正在学习如何使用NSUserDefault并拥有一个应用程序,用户可以在其中添加/删除tableviewcell,剩下的将保存到NSUserdefault中。添加部分工作正常,但删除部分给我一些麻烦(它没有删除)

我想知道我的代码在哪里犯了一个导致这个问题的错误。感谢您的帮助

编辑:我已经尝试过设置defaults.set(self.exchange.currencyToGetExchangesDictionary.keys,forKey:" currency")但是,当我删除行时,Xcode给了我一个与高度相关的错误iirc。我已经在删除的行上尝试了tableview.reload(),但正如我在其他问题上看到的那样,我们不应该这样做。

 override func viewDidLoad() {
    super.viewDidLoad()
    var savedArray = defaults.object(forKey: "currencies")
    if  savedArray != nil {
        savedArray = Array(self.exchange.currencyToGetExchangesDictionary.keys)
        self.initialRetrievingAndSavingData()
    } else {
        self.exchange.currencyToGetExchanged = ["USD","EUR","GBP"]
        self.initialRetrievingAndSavingData()
    }
}
// Tableview Functions-----------------------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.exchange.currencyToGetExchangesDictionary.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "currencyExchangeCell", for: indexPath) as? CurrencyExchangeTableViewCell
    let sortedKeys = Array(self.exchange.currencyToGetExchangesDictionary.keys)
    let sortedValues = Array(self.exchange.currencyToGetExchangesDictionary.values)
    cell?.currencyLabel.text = sortedKeys[indexPath.row]
    cell?.exchangeValueLabel.text = sortedValues[indexPath.row]
    defaults.set(sortedKeys, forKey: "currencies")
    return cell!
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow!
    let cell = tableView.cellForRow(at: indexPath) as? CurrencyExchangeTableViewCell
    valueToPass = Array(self.exchange.currencyToGetExchangesDictionary.keys)[indexPath.row]
    self.getPastData(currency: valueToPass)
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        self.exchange.currencyToGetExchangesDictionary.removeValue(forKey: Array(self.exchange.currencyToGetExchangesDictionary.keys)[indexPath.row])
        print(self.exchange.currencyToGetExchangesDictionary)
        currencyExchangeListTableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

我的打印结果是在删除USD单元格之后:

["EUR": "8,771.5230", "GBP": "7,688.9664"] 

然而,当我再次打开应用程序时,它仍然有美元EUR

0 个答案:

没有答案