SwiftUI List updating from Method

120 views Asked by At

please consider the following swiftUI scenario:

List {
  ForEach(manager.items(filter: .all), id: \.id) { item in
    RowView(item: item)
  }
}

where manager is an environment object injected via @EnvironmentObject var manager: Manager. The items() method returns an array of core data entities fetched depending on the filter parameter. This works well for mutating elements, but whenever an element is added or removed, the ForEach view is not notified (of course, because its a function return and no "binding" or such).

Whet is the bes practice approach to update the list accordingly? Can I somehow wrap the function call? Or notify about changes? Any tip is appreciated!

2

There are 2 answers

5
P. A. Monsaille On

I'm not sure how this behaves with core data fetching and how well it performs, but you can try to bind your fetch results like this:

    //...

    private var items: Binding<[ItemType]> { Binding (
        get: { self.manager.items(filter: .all) },
        set: { _ in }
    )}
    
    var body: some View {
        
        List {
            ForEach(self.items, id: \.id) { item in
                RowView(item: item)
            }
        }

    //...

Or:

    List {
        ForEach(self.items.wrappedValue, id: \.id) { item in
            RowView(item: item)
        }
    }

With Swift 5.3, referencing with self. can be omitted.

1
Hunter Meyer On