|
I have had anissue with a re-implementation of an app using SwiftData. I finally reproduced it in a simple adaptation of Apple's boilerplate SwiftData app so either there is a bug in SwiftData, or, more likely, I am not understanding fully contexts and scope... The issue revolves around putting methods and computed vars in the data model (classes). This code uses a computed var to count the number of SubItems in an Item, and a method to add a new SubItem. The view that shows the subItems demonstrates that the method is not getting the updated number of SubItems. Restarting the App sets the count correctly. The image shows the result of two runs of the App. ![https://share.icloud.com/photos/001U6S7ve3MkqPpLTDTXDbYQQ]
|
|
hi, i would change three things:
so here's my simplification of Item.addSubItem()
change to SubItem:
and final version of ItemView:
i think i got all the highlights here ... let me know if i have missed anything and i'll put up the full code for you. hope that helps, DMG |
|
Thanks DMG. That worked. Now I need to understand why! Did the extra @Query create a new "context?" that was updated separately from that used in ContentView? BTW I thought it was unwise to specify both sides of a relationship with @Relationship? I think it was in Paul's SwiftData that he said specifying the inverse was a good idea in all cases, but only on one side. Gerry |
|
hi Gerry, (1) i think the extra query was simply not necessary, because the subItems of an Item are already known when you enter the (2) i think the major issue was (3) i think the sequence of linking a new SubItem to an Item should always look like this:
i think it makes clear to the Observation framework that there's a dependency here that needs to be obseerved. at least in the early betas, i think this alternative linking sequence (well known to Core Data users)
just did not make an Item responsive to changes in the subitems. perhaps this will change in the future. (4) as for both sides of the relationship, you certainly cannot specify each as the hope that helps, DMG |
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.