Skip to content

Commit 78bf670

Browse files
committed
Line up contexts when setting a toOne
Might want to have that for toMany as well, not sure whether that gives perf issues. Maybe just check the first.
1 parent f9eb134 commit 78bf670

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Sources/ManagedModels/PersistentModel/PersistentModel+KVC.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,21 @@ public extension PersistentModel {
120120
func _setOptionalToOneValue<T>(forKey key: String, to model: T?)
121121
where T: PersistentModel
122122
{
123+
#if DEBUG
124+
let relship = Self._$entity.relationshipsByName[key]!
125+
assert(!relship.isToMany, "relship: \(relship)")
126+
#endif
127+
if let model {
128+
if model.modelContext != self.modelContext {
129+
if let otherCtx = model.modelContext, self.modelContext == nil {
130+
otherCtx.insert(self)
131+
}
132+
else if let ownCtx = self.modelContext, model.modelContext == nil {
133+
ownCtx.insert(model)
134+
}
135+
}
136+
}
137+
123138
willChangeValue(forKey: key); defer { didChangeValue(forKey: key) }
124139
if let model {
125140
setPrimitiveValue(model, forKey: key)

0 commit comments

Comments
 (0)