groue / GRDBCombine

GRDB ❤️ Combine
MIT License
223 stars 16 forks source link

TransactionObserver nil when using with SwiftUI #23

Closed jun1st closed 4 years ago

jun1st commented 4 years ago

Try using GRDBCombine with inside a SwiftUI view,

I start my observation inside my view model:

var spendingObserver: TransactionObserver?

init() {
    ....
    let observation = ValueObservation.tracking(value: { db in
                                try Outcome.fetchAll(db, sql: "select cost from outcome where date >= ?", arguments: [startOf15DaysAgo])
                            })
    self.spendingObserver =
            try! observation.start(in: databasePool, onChange: { outcomes in

                self.todayTotal =
                    outcomes.filter { (outcome) -> Bool in
                        outcome.date >= startOfToday
                    }.map({ (outcome) -> Double in
                        outcome.cost
                    }).reduce(0, +)

                self.yesterdayTotal =
                    outcomes.filter({ (outcome) -> Bool in
                            outcome.date < startOfToday && outcome.date >= (startOfToday - 1.days)
                    }).map({ (outcome) -> Double in
                        outcome.cost
                    }).reduce(0, +)
            })
    ...
}

use the viewmodel inside SwiftUI View.

 @ObservedObject var viewModel = UserSpendingViewModel()

 ...

SpendingSection(title: "Today", total: viewModel.todayTotal)
# it shows the data correctly

But when I try to insert a new record to database. It fails ACCESS_BAD_ADDRESS, debug view shows as follows, looks like it needs a strong reference?

Screen Shot 2019-11-18 at 2 03 56 PM
groue commented 4 years ago

Hello @jun1st,

If you are using Xcode 11.2, then set DEAD_CODE_STRIPPING to NO in the build settings of your app. This is a workaround for a Xcode bug, see https://github.com/groue/GRDB.swift/issues/640#issuecomment-548975256.

jun1st commented 4 years ago

@groue set DEAD_CODE_STRIPPING to No fix the issue.

thanks for the quick response and the awesome GRDB library 👍 👍