2

I'm making app in SwiftUI. I have following model:

struct Transaction {
    var title: String
    var category: TransactionCategory
    var value: Double
    var date: Date
    let id = UUID()
}
class Account: ObservableObject {
    
    var name: String = ""
    var currency: String = ""
    let id = UUID()
    @Published var balance: Double = 0
    @Published var trancactions: [Transaction] = []
}

and this works I expected. I can add new transaction and list all transactions in SwiftUI List view.

Now I'd like to add AccountManager to keep many account:

class AccountManager: ObservableObject {
    @Published var accounts: [Account] = []
}

but when I try for example add and display all transaction from choosen account, it doesn't refresh.

@ObservedObject private var manager =  AccountManager()

...

List(manager.accounts[0].trancactions, id: \.id) { t in
     TransactionRow(transaction: t)
}

Ultimately, I want to be able to display all transactions from all accounts or filter them. Is my idea fixable or maybe I need to try a different approach?

mateuszm7
  • 49
  • 6
  • FIrst off I recommend using `@StateObject` over `@ObservableObject`. But beyond that. A way I have solved this is by putting a view model in the TransactionRow as well. So basically each TransactionRow would also have its own `@StateObject`. – aeskreis Sep 10 '21 at 15:44
  • Account needs to be observed on its own. You can observe the individual items in the array like this – lorem ipsum Sep 10 '21 at 16:25
  • @aeskreis what you would keep in `@StateObject` in TransactionRow? – mateuszm7 Sep 11 '21 at 06:24
  • The TransactionRow `@StateObject` would be the `Account` – aeskreis Sep 13 '21 at 14:16

0 Answers0