I have two different VersionedSchema accessed via two different and distinct in-memory ModelContainers. However, both schemas have a model named Item.
LocalSchema.Item and RemoteSchema.Item have slightly different properties.
If I create and save RemoteSchema.Item in one context then I cannot create and save LocalSchema.Item in a different context due to missing origin property.
enum LocalSchema: VersionedSchema {
static var versionIdentifier: Schema.Version = .init(1, 0, 0)
static var models: [any PersistentModel.Type] = [
Item.self
]
@Model
class Item {
@Attribute(.unique)
var title: String
var created: Date
var modified: Date
init(title: String, created: Date, modified: Date) {
self.title = title
self.created = created
self.modified = modified
}
}
}
enum RemoteSchema: VersionedSchema {
static var versionIdentifier: Schema.Version = .init(1, 0, 0)
static var models: [any PersistentModel.Type] = [
Item.self
]
@Model
class Item {
var title: String
var created: Date
var modified: Date
var origin: String
init(title: String, created: Date, modified: Date, origin: String) {
self.title = title
self.created = created
self.modified = modified
self.origin = origin
}
}
}
In the above example, saving RemoteSchema.Item will cause LocalSchema.Item to fail.
The error message I see is
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSManagedObject 0xa120f3750> setValue:forUndefinedKey:]: the entity Item is not key value coding-compliant for the key "origin".'
Test Code
@Test func createLocalItemWithManualSave() async throws {
let context = ModelContext(try localStore())
let item = LocalSchema.Item(title: "local", created: .now, modified: .now)
context.insert(item)
try context.save()
}
@Test func createRemoteItemWithManualSave() async throws {
let context = ModelContext(try remoteStore())
let item = RemoteSchema.Item(title: "remote", created: .now, modified: .now, origin: "from space")
context.insert(item)
try context.save()
}
func localStore() throws -> ModelContainer {
let schema = Schema(versionedSchema: LocalSchema.self)
let config = ModelConfiguration("local", schema: schema, isStoredInMemoryOnly: true, allowsSave: true, cloudKitDatabase: .none)
return try ModelContainer(for: schema, configurations: config)
}
func remoteStore() throws -> ModelContainer {
let schema = Schema(versionedSchema: RemoteSchema.self)
let config = ModelConfiguration("remote", schema: schema, isStoredInMemoryOnly: true, allowsSave: true, cloudKitDatabase: .none)
return try ModelContainer(for: schema, configurations: config)
}
I have created FB22310365