Reputation: 738
I have a list
List {
ForEach (appState.foo.indices, id: \.self) { fooIndex in
Text(foo[fooIndex].name)
}
.onDelete(perform: self.deleteRow)
}
with a function that deletes a row from the foo
array:
private func deleteRow(at indexSet: IndexSet) {
self.appState.foo.remove(atOffsets: indexSet)
}
and an observable object that acts as an environment object in the view with the list:
class AppState: ObservableObject {
var foo: [Bar] {
set {
if let encoded = try? JSONEncoder().encode(newValue) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: "foo")
}
objectWillChange.send()
self.myFunc()
}
get {
if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data,
let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
return loadedTraining
}
return []
}
}
// ....
func myFunc() {
print("I'm not printing when you delete a row")
}
}
How can I get my myFunc()
triggered when I delete a row?
Upvotes: 0
Views: 63
Reputation: 16361
Use stored property instead of a computed property. To fix your issue modify the foo
property in AppState
like this:
struct Bar: Encodable { }
class AppState: ObservableObject {
var foo: [Bar] {
didSet {
if let encoded = try? JSONEncoder().encode(foo) {
UserDefaults.standard.set(encoded, forKey: "foo")
}
objectWillChange.send()
myFunc()
}
}
init() {
if let data = UserDefaults.standard.data(forKey: "foo"),
let savedFoo = try? JSONDecoder().decode([Bar].self, from: data) {
foo = savedFoo
} else {
foo = []
}
}
func myFunc() {
print("I'm not printing when you delete a row")
}
}
Upvotes: 1