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

SOLVED: Why do I get a "Publishing changes from within view updates is not allowed, this will cause undefined behavior" error

Forums > SwiftUI

I'm borrowing a pattern from Paul's UltimatePortfolio app in which I have DataController that handles all things CoreData and it has a @Published var selectedLiftEvent: LiftEvent? (similar to @Published var selectedIssue: Issue? in Paul's project)

I know this error typically occurs when you're trying to update a @Published property within a SwiftUI view's lifecycle methods, such as init(), onAppear(), or onChange() of another @ObservedObject, but I don't think I'm doing any of this in CalculatorView. Am I wrong?

I'm using the 'LiftEvent' in CalculatorView like this:

struct CalculatorView: View {
    @EnvironmentObject var dataController: DataController
    @ObservedObject var liftEvent: LiftEvent

    @State private var showPercentages = false
    @State var units: String = "kg"
    @State private var oneRepMax: String = "0.0"

    private let weightCharacterLimit = 3
    private let repsCharacterLimit = 2

    let calculator = Calculator()

    var body: some View {

        NavigationView {
            ZStack {
                VStack {
                    Text(oneRepMax)
                        .font(.system(size: 90, weight: .light))
                        .foregroundColor(.yellow)

                    HStack {
                            HStack() {
                                TextField("Weight", text: $liftEvent.eventWeight)
                                    .keyboardType(.decimalPad)
                                    .onChange(of: liftEvent.eventWeight) { _, newValue in
                                        if liftEvent.eventWeight.count > weightCharacterLimit {
                                            liftEvent.eventWeight = String(liftEvent.eventWeight.prefix(weightCharacterLimit))
                                        }
                                        updateOneRepMax()
                                    }

                                Text($units.wrappedValue)
                            }
                        }

                        VStack {
                            Text("Reps")
                                .font(.system(size: 20, weight: .medium))
                                .foregroundColor(.white)

                            TextField("Reps", text: $liftEvent.eventReps)
                                .keyboardType(.decimalPad)
                                .onChange(of: liftEvent.eventReps) { _, newValue in
                                    if liftEvent.eventReps.count > repsCharacterLimit {
                                        liftEvent.eventReps = String(liftEvent.eventReps.prefix(repsCharacterLimit))
                                    }
                                    updateOneRepMax()
                                }

                        }
                    }
                    .padding(.top, 20)
                    .sheet(isPresented: $showPercentages) {
                        PercentagesView()
                            .presentationDetents([.medium, .large])
                    }
                    Spacer()
                }
                .onChange(of: liftEvent.eventWeight) { _, newValue in
                    updateOneRepMax()
                }
                .onChange(of: liftEvent.eventReps) { _, newValue in
                    updateOneRepMax()
                }
            }
            .toolbar(content: CalculatorViewToolbar.init)
        }
    }

    private func updateOneRepMax() {
        oneRepMax = String(format: "%.1f", calculator.calculateOneRepMax(weight: Double(liftEvent.eventWeight) ?? 0, reps: Int(liftEvent.eventReps) ?? 0, formula: UserDefaults.formulaName()))
    }

}

The problem is that I get the error here:

    func newLiftEvent() {
        let liftEvent = LiftEvent(context: container.viewContext)
        liftEvent.uuid = NSUUID().uuidString
        liftEvent.date = .now
        liftEvent.formula = defaultFormula()
        liftEvent.lift = defaultLift()
        liftEvent.weightUnit = UserDefaults.unitsNotation().weightUnit

        selectedLiftEvent = liftEvent // ERROR: Publishing changes from within view updates is not allowed, this will cause undefined behavior.
    }

But this function is doing essentially the same thing as Paul's function for creating a new Issue:

    func newIssue() {
        let issue = Issue(context: container.viewContext)
        issue.title = NSLocalizedString("New issue", comment: "Create a new issue")
        issue.creationDate = .now
        issue.priority = 1

        // If we are currently browsing a user-created tag, immediately
        // add this new issue to the tag otherwise it won't appear in
        // the list of issues they see.
        if let tag = selectedFilter?.tag {
            issue.addToTags(tag)
        }

        save()

        selectedIssue = issue // No error
    }

   

Thanks for the suggestions, @Obelix. I added 'save()' (and the functions it needs to work) so it exactly matches what Paul is doing but, as I suspected, it didn't fix the problem.

About the .onChange(of: liftEvent.eventWeight), I actually didn't miss what Paul was saying about the job of views. I believe that he's absolutely correct. The code in that modifier limits the number of characters a user can input (which you probably figured out) and I didn't consider that business logic.

I don't think it makes sense to move it to the LiftEvent because LiftEvent can accept much larger numbers for the eventWeight and eventReps properties. Limiting the characters a user can input is purely a UI thing. I do think it might make sense to have that code in a ViewModifier though.

Let me know if you think otherwise.

   

You're in the elite HWS+ community. Us plebes in the lower decks don't get to see the articles for his Ultimate Portfolio. Nor can we view the vids he posts as solutions to his HWS+ Ultimate Portfolio.

To be honest, I was just taking a wild guess as I can't see his code, nor his solutions. Since it didn't work, I deleted my unhelpful post.

   

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!

I can't see the context in which newLiftEvent is being called. Are you sure you're on the main thread? I have had similar problems in one of my apps and the solution was to save the changed object, then set the selected item inside a DispatchQueue.main.async callback. It then forces the update onto the main thread where the UI updates. Might be worth. try.

   

@barnettsab, I'm not sure if I'm on the main thread. I'm not very knowledgeable about multi-threading to be honest. Is there an easy way for me to tell?

   

Wrap the code and see if it makes a difference.

DispatchQueue.main.async {
  selectedLiftEvent = liftEvent
}

If you are on the main thread, then there is no significant overhead. If not, the code will just run and your update should happen without error. The overhead of testing which thread you're on is wasted effort. Chances are, if you're not on the main thread and this fixes your problem, then you're always going to be on another thread so the test becomes irrelevant.

2      

I encourage the OP to buy Paul's "Swift Concurrency by Example". I think it is the clearest book he's written. It explains the basis of @barnettsab's advice.

   

@JackAward, since the LiftEvent managed object properties are binded to the TextFields, is it possible to separate view updates from data changes?

   

Thanks, @Barnettsab. That made the warning go away so it must have not been running on the main thread.

   

No worries. I suspect you are calling this code from a closure and that closure is from a background activity. Without seeing the code where your method is called, I can only guess (and offer the same fix that I did in my own code).

   

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.