@spellcasterdragonborn
Hah, Apple uses the underscore to format italic text, so when I type your name in here the underscores cause formatting chaos.
Yes, at this current moment in time, I agree with you - there is no need to use
@StateObject.
So to be clear, at this current moment in time, I understand that
ALL WE NEED to access Core Data features throughout our SwiftUI
App is an
NSManagedObjectContext.
To answer your question the long way round...
Apple does not let us edit our answers so when I wrote my original answer, this was all fairly new to me. If I could change the answer - as I have in my SwiftUI universal apps that use Core Data - I would change the following...
Code Block lazy var persistentContainer: NSPersistentContainer = {...} |
Change to:Code Block private lazy var persistentContainer: NSPersistentContainer = {...} |
My reason is that there are only three properties that I believe should be publicly available in my
class implementation of
PersistentStore...
static let shared, ...and through this one line singleton...
var context, to use throughout the app; and
func save, for convenience.
If you check Apple's response to my forum question with the abstract title
New toolbar appearance in macOS 11, you can see their advice "and then your SwiftUI App could hold on to an instance of that (ed. custom) class in a variable." In their response, they also suggest I should watch the
SwiftUI Data Essentials WWDC session for inspiration. From my multiple viewings of this session, at the time I deducted that the hint was to use an
@StateObject for my
PersistentStore class, which is why I included it in my Core Data SwiftUI Xcode projects and in my original answer. It also made it easy for me to call
save from the
.onChange(of: scenePhase) view modifier.
In hindsight and following review of the template that Apple includes in more recent Xcode 12 betas, I was complicating their hint. (As per Apple's beta Core Data template) the instance of that persistent container custom class could be as simple as...
Code Block let persistenceController = PersistenceController.shared |
or, per my previous answer...
Code Block let persistentStore = PersistentStore.shared |
However, at this current moment in time, I would remove the
@StateObject instance of my
PersistentStore class. Not that I have done that yet in my SwiftUI projects (no reason, just not got around to it). It seems important for me to add subtext here - I am still developing an understanding of how
@StateObject property wrapper operates in the
App lifecycle, so in the future and with a better understanding, I might change this decision.
(PS: I just commented out
@StateObject private var persistentStore = PersistentStore.shared in one project as a test and my iOS and macOS targets appear to build and run without issue. There seems to be a minor drop in memory usage, but this is speculative without taking steps to measure it properly.)