TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: help with updating the data SwiftUI

Forums > SwiftUI

@Genka  

Please help me, my data in the diogram is updated only after restarting the application, what am I doing wrong??? Please describe in detail my mistake where it is necessary and what should be changed?

I'm trying to move this data into my chart

struct ExpenseItem: Identifiable, Codable {
    var id = UUID() // присваеваем каждой затрате уникальный идендификатор
    let name: String
    let type: String
    let amount: Int
    let service: Int
    let type3: String

}

//создаем класс который будет хранить массив затрат в одной переменной
//будет кодировать и раскодировать данные
class Expenses: ObservableObject {
    @Published var items = [ExpenseItem]() {
        didSet {
            let encoder = JSONEncoder()
            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() {
        if let items = UserDefaults.standard.data(forKey: "Items") {
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([ExpenseItem].self, from: items) {
                self.items = decoded
                return
            }
        }
    }
}

struct MaintenanceDataView: View {
    // Для того что бы использовать индификатор .sheet() переход спомощью листа
    @State private var showingAddExpense = false
    // Говорим SwiftUI наблюдать, когда у нас @Published var items = [MaintenanceItems]() меняется, то и  все вью будет обновляться
    @ObservedObject var  expenses = Expenses()

    var body: some View {
        NavigationStack {
            List {
                //Говорим свифту что бы он идендифицировал каждую затрату по имени
                ForEach(expenses.items)  { item in
                    Section(item.name) {
                        HStack {
                            VStack(alignment: .leading) {
                                Text("Проводилось на \(item.amount) \(item.type3)")
                                Spacer(minLength: 1)
                                Text("Следующее на \(item.amount + item.service) \(item.type3)")
                                    .font(.system(size: 11))
                                    .foregroundColor(.gray)

                            }

                            Spacer(minLength: 50)
                            HStack {
                                Text(item.type)
                                    .font(.caption2)
                                    .foregroundStyle(.white)
                                    .padding(.horizontal, 10)
                                    .padding(.vertical, 10)
                                    .background(.red.gradient, in: .capsule)
                            }
                        }
                    }

                }

                .onDelete(perform: removeItems2) //удаление строчек

            }

            .overlay {
                if expenses.items.isEmpty {
                    ContentUnavailableView {
                        Label("Данные по ТО не найдены", systemImage: "oilcan.fill")
                    }

                }

            }

            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        showingAddExpense.toggle()
                    } label: {
                        HStack {
                            Image(systemName: "plus.circle")
                                .resizable()
                                .frame(width: 30, height: 30)

                        }
                    }

                }
            }
            .listStyle(.insetGrouped)
            .sheet(isPresented: $showingAddExpense) {
                AddMaintenancesView(expenses: self.expenses) //помещаем созданное нами вью
            }
            .navigationBarTitle("Обслуживание")

        }
    }
    // Функция удаления
    func removeItems2(as ofsets: IndexSet) {
        expenses.items.remove(atOffsets: ofsets)
    }
}

struct MaintenanceDataView_Previews: PreviewProvider {
    static var previews: some View {
        MaintenanceDataView()
    }
}

they are added only if I restart the application, here is the diagram itself

truct MaintenanceAnalytics: View {
    @State var  expenses = Expenses()
    @State private var isShowingItemScheet = false
    @EnvironmentObject var truth: Expenses
    @State var count = 0
    var body: some View {
        VStack(alignment: .leading,spacing: 4) {
            Text("Записей техническо обслуживания: \(expenses.items.count)")
                .fontWeight(.semibold)
                .font(.footnote)
                .foregroundColor(.secondary)
                .padding(.bottom, 12)

            Chart {
                ForEach(expenses.items) { item in
                    SectorMark(
                        angle: .value("", item.amount), innerRadius: .automatic,
                        angularInset: 1.5
                    )
                    .cornerRadius(50)
                    .foregroundStyle(by: .value("", item.name))
                    .annotation(position: .overlay,content: {
                        Text("\(item.amount)")
                            .font(.system(size: 8))

                    })

                }
            }

            .frame(height: 200)
        }
        .overlay {
            if expenses.items.isEmpty {
                ContentUnavailableView(label: {
                    Label("Нет данных ", systemImage: "oilcan.fill")
                        .font(.system(size: 15))
                }, description:  {
                    Text("Добавьте данные в меню по техническому обслуживанию автомобиля")
                })

            }

        }
    }
    }

#Preview {
    MaintenanceAnalytics()
}

2      

Hi! Not sure how you pass reference to the object in different views, as you showcased only couple of them but without full picture it is difficult to judge what is wrong. But from the outset i can say that

Here MaintenanceDataView you create new object:

@ObservedObject var  expenses = Expenses()

Then again in MaintenanceAnalytics create new object

@State var  expenses = Expenses()

and besides access this item from the environment... @EnvironmentObject var truth: Expenses But where do you inject the object to environment?

so which object are you trying to access then?

I think the logic should be better handled this way. Of course it is quite simplified example but you can see how the reference to object "state of truth" is passed around and modifications are published and available in any view.

// This is your object
class MyObject: ObservableObject, Observable {
    @Published var count = 0

    func addToObject() {
        count += 1
    }
}

struct ContentView: View {
    // This is the state of truth for your object it HAS to be @StateObject but not @ObservedObject
    @StateObject var myObject = MyObject()

    var body: some View {
        NavigationStack {
            VStack(spacing: 10) {
                Text("\(myObject.count)")

                Button("Add to Object") {
                    myObject.addToObject()
                }

                NavigationLink("Go to SecondView") {
                    SecondView(myObject: myObject)
                }
            }
        }
        // You can also inject the object to the environment
        // and it will be accessible anywhere in the NavigationStack
        .environment(myObject)
    }
}

struct SecondView: View {
    // If you use @ObservedObject you cannot initialize it again as it will create new object
    // you have to pass the reference to the object's state of truth only
    @ObservedObject var myObject: MyObject

    var body: some View {
        NavigationStack {
            VStack(spacing: 10) {
                Text("\(myObject.count)")

                Button("Add to Object") {
                    myObject.addToObject()
                }

                NavigationLink("Go to ThirdView") {
                    ThirdView()
                }
            }
        }
    }
}

struct ThirdView: View {
    // As you have myObject injected in the environment you can access it from there like so:
    @EnvironmentObject var myObject: MyObject

    var body: some View {
        NavigationStack {
            VStack(spacing: 10) {
                Text("\(myObject.count)")

                Button("Add to Object") {
                    myObject.addToObject()
                }
            }
        }
    }
}

3      

Please help me I've also same issue.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.