Wizzardzz
Wizzardzz

Reputation: 841

Delete NSUserDefaults to corresponding UITableViewCell

I am trying to reinitialize all the data associated with a given cell when this one is deleted.

This is my function deleting the cell (cryptosArray is the array creating the cells):

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            cryptosArray.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            let userDefaults = UserDefaults.standard
            let encodedData : Data = NSKeyedArchiver.archivedData(withRootObject: cryptosArray)
            userDefaults.set(encodedData, forKey: "cryptosArray")
            userDefaults.synchronize()


        }
    }

And this is a function that saves the amount entered in the textfield present in the cell:

    func cellAmountEntered(_ walletTableViewCell: WalletTableViewCell, cryptoPrice: String) {

        if walletTableViewCell.amountTextField.text == "" {
            return
        }
        let str = walletTableViewCell.amountTextField.text

        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "en_US")
        let dNumber = formatter.number(from: str!)
        let nDouble = dNumber!
        let eNumber = Double(truncating: nDouble)

        walletTableViewCell.amountLabel.text = String(format:"%.8f", eNumber)
        UserDefaults.standard.set(walletTableViewCell.amountLabel.text, forKey: "\(cryptoPrice)Amount")
        walletTableViewCell.amountTextField.text = ""

    }

As you can see I am saving walletTableViewCell.amountLabel.text with "\(cryptoPrice)Amount" inside the UserDefaults file where \(cryptoPrice) is a parameter corresponding to the cell.

How can I delete the corresponding "\(cryptoPrice)Amount" key when I delete the cell? I can't figure out how to pass the parameter to commit editingStyle: ..

Upvotes: 0

Views: 83

Answers (1)

Tung Fam
Tung Fam

Reputation: 8147

The basic solution is: create an array of cryptoPrices. Each cell should have a value in there. For example, you can initialize an array with all zeros (if it works for you I don't know). Then if user enters the amount, you delete the zero from the array and .insert a new value there. So then when you do deletion you may easily find your key by indexPath.row.

Hope it helps! But note: this is a very straightforward solution.

I would do this: don't use UserDefaults for such things. It's not a DataBase. Better to use Realm or CoreData. I understand that it's harder but there are many tutorials that may help you with that. Good luck! Hope it helps.

Upvotes: 1

Related Questions