I try to observe my array of custom objects in my UserDefaults using a Combine
publisher.
First my extension:
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")
}
}
}
Then in my View model, within my init()
I do:
UserDefaults.standard
.publisher(for: \.ratedProducts)
.sink { ratedProducts in
self.ratedProducts = ratedProducts
}
.store(in: &subscriptions)
You can see that I basically want to update my @Published
property ratedProducts
in the sink call.
Now when I run it, I get:
Fatal error: Could not extract a String from KeyPath Swift.ReferenceWritableKeyPath<__C.NSUserDefaults, Swift.Array<RebuyImageRating.Product>>
I think I know that this is because in my extension the ratedProduct property is not marked as @objc
, but I cant mark it as such because I need to store a custom type.
Anyone know what to do?
Thanks