简体   繁体   中英

Removing Custom Objects from List in UserDefaults

I am trying to remove an element from a list which is stored in NSUserDefaults. The getAll function is implemented below:

  func getAllOrders() -> [Order] {

        var orders = [Order]()

        if let userDefaults = UserDefaults(suiteName: "group.com.johndoe.SoupChef.Shared") {

            if let ordersData = userDefaults.data(forKey: "Orders") {
                orders = try! JSONDecoder().decode([Order].self, from: ordersData)
            }
        }

        return orders
    }

And here is the code for deleting the order.

func delete(order :Order) {

        var persistedOrders = getAllOrders()

        persistedOrders.removeAll { persistedOrder in
            persistedOrder.identifier.uuidString == order.identifier.uuidString
        }

    }

After deleting the order in the code above when I call getAllOrders I still see all the elements, meaning I don't see the order being deleted.

That's because you don't save your changes. Once you've performed the removal you need to turn persistedOrders back into JSON and then:

userDefaults.set(json, forKey:"Orders")

You need to use jsonEncoder and encode the edited array then store it again the user defaults

func delete(order :Order) {

    var persistedOrders = getAllOrders()

    persistedOrders.removeAll { persistedOrder in
        persistedOrder.identifier.uuidString == order.identifier.uuidString
    }
    do {

        let data = try JSONEncoder().encode(persistedOrders)
        userDefaults.set(data, forKey:"Orders")
    }
    catch {

        print(error)
    }

}

You have to store correctly your UserDefaults

UserDefaults.standard.set(json, forKey:"Orders")

Now, you can remove them using:

UserDefaults.standard.removeObject(forKey: "Orders")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM