Core Data Count SwiftUI

310 Views Asked by At

When I add a new reminder to my list I can not see the count + 1 simultaneously. But when I re-run the program I see the count is correct.

https://vimeo.com/545025225

    struct ListCell: View {
    var list : CDListModel
    @State var count = 0
    @State var isSelected: Bool = false
    var body: some View {
        HStack{
            Color(list.color ?? "")
                .frame(width: 30, height: 30, alignment: .center)
                .cornerRadius(15)
            Text(list.text ?? "")
                .foregroundColor(.black)
                .font(.system(size: 20, weight: .regular, design: .rounded))
            Spacer()
            Text(String(count))
                .foregroundColor(.gray)
                .onAppear{
                    DispatchQueue.main.async {
                        self.count = list.reminders!.count
                    }
                }
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

If CDListModel is a CoreData entity, then you can just add this:

@ObservedObject var list : CDListModel

Also remove the State for the count.

Then display the count like this:

Text(String(list.reminders!.count))

As hint: I wouldn't use force unwrapping aswell. Maybe provide a default value instead of force unwrapping