Home > Blockchain >  How to delete rows from UITableView and update array from UserDefaults in Swift / iOS
How to delete rows from UITableView and update array from UserDefaults in Swift / iOS

Time:09-16

I have gone through This is the appearance like

CodePudding user response:

You are trying to operate on non-property list object.

You have to follow below mentioned steps:

  1. Parse your cart data from UserDefaults according to "[CartStruct]"

  2. Check and delete It.

  3. Update after deletion to UserDefaults

  4. Reload your TableView

     func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
         if editingStyle == .delete {
             cartArray = self.updateCartItems(name: cartArray[indexPath.row].cartItems.name)
             tableView.deleteRows(at: [indexPath], with: .fade)
         }
     }
    

Here, You need to check and delete:

   func updateCartItems(name: String) -> [CartStruct] {
        guard var cartItems = self.getCartData() else { return [] }
        cartItems = cartItems.filter({ $0.cartItems.name != name })
        if let updatedCart = try? PropertyListEncoder().encode(cartItems) {
            UserDefaults.standard.set(updatedCart, forKey: "cartt")
        }
        UserDefaults.standard.set(cartItems.count, forKey: "CountAddedProducts")
        return cartItems
      }
  • Related