Background: I had an old CoreData, document-based app where it was expected each document would apply to a specific year, in a specific state/province. It made the most sense to save the year and location on a per-document basis, outside of the CoreData model. I managed use the document’s metadata dictionary, accessed via the NSPersistentStore, as described in this question: How can document-based settings be stored?
In more detail, the code looked like this:
class Document: NSPersistentDocument {
//other let/var here
var persistentStore: NSPersistentStore? {
if let stores = self.managedObjectContext?.persistentStoreCoordinator?.persistentStores {
if stores != [] {
return stores[0]
}
}
return nil
}
@objc dynamic var documentYear = 2011 {
didSet {
setMetaData(documentYear as AnyObject, forKey: "year")
}
}
@objc dynamic var documentProvince = 3 {
didSet {
setMetaData(documentProvince as AnyObject, forKey: "province")
}
}
func setMetaData(_ object: AnyObject, forKey key: String) {
if persistentStore != nil {
var metadataDict = persistentStore!.metadata
if metadataDict?[key] == nil || (metadataDict?[key] as! NSNumber) != (object as! NSNumber) {
metadataDict?[key] = object
persistentStore!.metadata = metadataDict
updateChangeCount(.changeDone)
}
}
}
func getMetaData() {
if persistentStore != nil {
let metadataDict = persistentStore!.metadata
if metadataDict?["year"] != nil {
documentYear = metadataDict?["year"] as! Int
}
if metadataDict?["province"] != nil {
documentProvince = metadataDict?["province"] as! Int
}
}
}
//other code here
}
I know it’s not exactly clean, but that’s not the point here…
Problem: Now updating to SwiftData, but trying to keep compatibility with my old files (even if I am basically the only user of this program).
I can’t find any documentation about an equivalent to NSPersistentStore in SwiftData/SwiftUI. This seems to mean I can’t get the metadata out of my old files (or create new document files with a SwiftUI version, using that previous method). The only mention of metadata in the SwiftData documentation seems to be on the persistent models themselves, which won’t help.
I can’t see how to subclass the persistent document in SwiftUI anyway, which means the previous method I used in the CoreData version wouldn’t work even if I did have an equivalent to NSPersistentStore. Additionally, if I can’t subclass the document, I don’t seem to have an alternative place to save document settings even outside the Persistent Store (if I were willing to break compatibility with old documents).
Question: Can document settings or metadata be used in SwiftData/SwiftUI, and if so, how? Is there a way to access the Persistent Store metadata that existed in my old CoreData files? Or is this something that just isn’t possible yet, pending this year’s WWDC, and my app’s migration to SwiftData will have to wait?