0

I want to keep track of my UserDefaults in my View model. To retrieve and add from my UserDefault, I currently do this.

extension UserDefaults {
    
    var ratedProducts: [Product] {
        get {
            guard let data = UserDefaults.standard.data(forKey: "ratedProducts") else { return [] }
            return (try? PropertyListDecoder().decode([Product].self, from: data)) ?? []
        }
        set {
            UserDefaults.standard.set(try? PropertyListEncoder().encode(newValue), forKey: "ratedProducts")
        }
    }
}

But now what I want to do is, having a published computed property in my View model that keeps track whenever an object is added. Which then should trigger an update in my progress bar within my view. How would I setup this property properly?

I thought of something like this. (Obviously this doesnt work)

@Published var ratedProducts: [Product] {
        ratedProducts = UserDefaults.standard.ratedProducts
}

Thanks for any help!

mike22
  • 33
  • 5
  • Just add objectWillChange.send() to your current set after the user defaults line. It will behave the same – lorem ipsum Aug 17 '22 at 14:22
  • 1
    Use AppStorage instead (either in view or in view model, now it is supported in ObservableObject as well). – Asperi Aug 17 '22 at 14:23
  • @loremipsum in which line exactly? In my Userdefaults extension or in my Published property in my view model? Because this won't work. – mike22 Aug 17 '22 at 14:47
  • @asperi I saw working with custom objects in AppStorage is a bit hacky. And you also need to consider appending object to the existing array in your UserDefaults. – mike22 Aug 17 '22 at 14:48
  • In the view model but user defaults isn’t the best place for arrays. It is the most insecure storage and it is in reliable it is meant for small insignificant things like volume settings, button order, etc. – lorem ipsum Aug 17 '22 at 19:18
  • Again. It depends on your use case. And you are wrong, you can store arrays. User defaults are plists basically. For example bookmarks. You can store them in there too. Nothing wrong with that. You store regular value types which do not hold so much size, maybe a few KB. And just to clarify because I see this often, other places like CoreData, SQLite or Documents do NOT make your data more secure ;). You still need some sort of encryption. – mike22 Aug 18 '22 at 07:46

0 Answers0