9

I looked through different questions here, but unfortunately I couldn't find an answer. This is my code:

SceneDelegate.swift

...
let contentView = ContentView(elementHolder: ElementHolder(elements: ["abc", "cde", "efg"]))
...
window.rootViewController = UIHostingController(rootView: contentView)

ContentView.swift

class ElementHolder: ObservableObject {

    @Published var elements: [String]

    init(elements: [String]) {
        self.elements = elements
    }
}

struct ContentView: View {

    @ObservedObject var elementHolder: ElementHolder

    var body: some View {
        VStack {

            ForEach(self.elementHolder.elements.indices, id: \.self) { index in
                SecondView(elementHolder: self.elementHolder, index: index)
            }

        }
    }
}

struct SecondView: View {

    @ObservedObject var elementHolder: ElementHolder
    var index: Int

    var body: some View {
        HStack {
            TextField("...", text: self.$elementHolder.elements[self.index])
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }

}

When pressing on the delete button, the app is crashing with a Index out of bounds error.

There are two strange things, the app is running when

1) you remove the VStack and just put the ForEach into the body of the ContentView.swift or

2) you put the code of the SecondView directly to the ForEach

Just one thing: I really need to have the ObservableObject, this code is just a simplification of another code.

UPDATE

I updated my code and changed Text to a TextField, because I cannot pass just a string, I need a connection in both directions.

2 Answers 2

8

The issue arises from the order in which updates are performed when clicking the delete button.

On button press, the following will happen:

  1. The elements property of the element holder is changed
  2. This sends a notification through the objectWillChange publisher that is part of the ElementHolder and that is declared by the ObservableObject protocol.
  3. The views, that are subscribed to this publisher receive a message and will update their content.
    1. The SecondView receives the notification and updates its view by executing the body getter.
    2. The ContentView receives the notification and updates its view by executing the body getter.

To have the code not crash, 3.1 would have to be executed after 3.2. Though it is (to my knowledge) not possible to control this order.

The most elegant solution would be to create an onDelete closure in the SecondView, which would be passed as an argument.

This would also solve the architectural anti-pattern that the element view has access to all elements, not only the one it is showing.

Integrating all of this would result in the following code:

struct ContentView: View {
    @ObservedObject var elementHolder: ElementHolder

    var body: some View {
        VStack {
            ForEach(self.elementHolder.elements.indices, id: \.self) { index in
                SecondView(
                    element: self.elementHolder.elements[index],
                    onDelete: {self.elementHolder.elements.remove(at: index)}
                )
            }
        }
    }
}

struct SecondView: View {
    var element: String
    var onDelete: () -> ()

    var body: some View {
        HStack {
            Text(element)
            Button(action: onDelete) {
                Text("delete")
            }
        }
    }
}

With this, it would even be possible to remove ElementHolder and just have a @State var elements: [String] variable.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks, that makes it clear, why the app crashes: SecondView will be informed first (I tried to set breakpoints, but I couldn't figure this out). Unfortunately your solution is not what I'm searching for, because my SecondView needs much more other properties of the ElementHolder, so I can't pass just a String... that is why your code is working, because the SecondView doesn't hold the ElementHolder
... and I have a TextField, not just a Text, please see my updated code
You could pass the item represented by each SecondView through a Binding. The binding works in two ways, so you pass the value from the ContentView to a SecondView and the SecondView passes changes back to the ContentView. Deletion would still have to be handled separately, as shown in my post. You can create a Binding using Binding<YourValue>(get: {self.elementHolder.elements[index]}, set: { newValue in self.elementHolder.elements[index] = newValue}). In the SecondView, there would have to be a variable @Binding var value.
@Lupurus Have you get any lucky? I have a same situation over here. A list contains elements and each of these elements shoudl have been binded through the views just to be able to update them in one view and publish those other views. It works like a charm without the onDelete
@Faruk: It doesn't work, if you use it with .indices. Just don't use .indices, you need to iterate over the elements themselves and then you have to work with .firstIndex(where: { $0.id == element.id }), if you want the index of each element
|
4

Here is possible solution - make body of SecondView undependable of ObservableObject.

Tested with Xcode 11.4 / iOS 13.4 - no crash

struct SecondView: View {

    @ObservedObject var elementHolder: ElementHolder
    var index: Int
    let value: String

    init(elementHolder: ElementHolder, index: Int) {
        self.elementHolder = elementHolder
        self.index = index
        self.value = elementHolder.elements[index]
    }

    var body: some View {
        HStack {
            Text(value)     // not refreshed on delete
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}

Another possible solution is do not observe ElementHolder in SecondView... for presenting and deleting it is not needed - also no crash

struct SecondView: View {

    var elementHolder: ElementHolder // just reference
    var index: Int

    var body: some View {
        HStack {
            Text(self.elementHolder.elements[self.index])
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}

Update: variant of SecondView for text field (only changed is text field itself)

struct SecondViewA: View {

    var elementHolder: ElementHolder
    var index: Int

    var body: some View {
        HStack {
            TextField("", text: Binding(get: { self.elementHolder.elements[self.index] },
                set: { self.elementHolder.elements[self.index] = $0 } ))
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}

4 Comments

Thank you! Solution 2 is nice, but I have a TextField, not just a Text ;) (that's the problem of simplifying code ;)). Solution 1 then has the same problem :( I'll update my code example.
Thank you very much!!
would it work with the onDelete modifier for ForEach other than dedicated button for to delete? @Asperi
Does this still work? It crashes for me on Xcode 12.5...

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.