Hi :-)
I´m looking for some help and advice for my little project. Basically I have a Tabview with 3 Tabs. One of them is a View for Favorites. I managed the selection and the saving of the favorites. However, the View for the Favorites is not updating while the app is running. Just when the app is closed and restarted the View of Favorites gets updated.
The Array of Favorites is marked with @Published, the variable in the Favorites-View is marked as @ObservedObject. I searched a lot and can't find my mistake.
„Expression“ is a Struct with about 10 properties.
Class for the Favorites:
class Favorites: ObservableObject {
@Published var favoriteExpressions: [Expression] = [] {
didSet {
print("Favorites changed")
}
}
private let saveKey = "FavoriteExpressions"
let defaults = UserDefaults.standard
init() {
if let data = defaults.data(forKey: saveKey) {
let decoder = JSONDecoder()
if let decoderSet = try? decoder.decode([Expression].self, from: data) {
favoriteExpressions = decoderSet
}
}
}
func contains() -> Bool {
}
func add() {
}
func remove() {
}
func save() {
defaults.set(try? PropertyListEncoder().encode(favoriteExpressions), forKey: saveKey)
let encoder = JSONEncoder()
if let encodedSet = try? encoder.encode(favoriteExpressions) {
defaults.set(encodedSet, forKey: saveKey)
}
}
View for the Favorites
struct View_Favoriten: View {
@ObservedObject var favoriten = Favorites()
var body: some View {
ZStack {
LinearGradient()
ScrollView {
LazyVGrid(columns: columns, alignment: .center, spacing: 10) {
ForEach(favoriten.favoriteExpressions.sorted(), id: \.self ) { expression in
VStack{
code for displaying data
}
.environmentObject(favoriten)
}
}
.padding(20)
}
}
.navigationBarHidden(false)
}
.accentColor(.accentColor)
}
The TabView:
struct ContentView: View {
var body: some View {
TabView {
View_Thema(expressions: Data)
.tabItem {
Image()
}
View_Favoriten()
.tabItem {
Image()
}
.environmentObject(Favorites())
Info_View()
.tabItem {
Image()
}
}
.environmentObject(Favorites())
}
}
You may observe that I’m saving the entire Expressions, instead of a key value. Previously i used to do that, but I suspected the calculated property (for getting the Structs related to the key value) maybe prohibiting the update of the View, therefore I’ve saved the entire Struct of Expression in an Array.
Thank you in advance! Cheers, Saxa