0

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?

1 Answer 1

1

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")
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Didn't know that this information was important: Within the setter I am saving the foo array to the user defaults. Thus I need the setter and you can't use didSet together with a setter
You can use didSet instead of set for that purpose. Just use foo instead of newValue.
Now I just need a solution for my getter that can't be use together with didSet.
Do the getting part in init. Check the init.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.