Remove incorrect workaround for crash when LazilyDecoding used on nil MO

This commit is contained in:
Shadowfacts 2023-12-04 16:20:22 -05:00
parent be1ca70ebf
commit 108a02826f
1 changed files with 26 additions and 40 deletions

View File

@ -33,41 +33,37 @@ public struct LazilyDecoding<Enclosing: NSManagedObject, Value: Codable> {
public static subscript(_enclosingInstance instance: Enclosing, wrapped wrappedKeyPath: ReferenceWritableKeyPath<Enclosing, Value>, storage storageKeyPath: ReferenceWritableKeyPath<Enclosing, Self>) -> Value {
get {
instance.performOnContext {
var wrapper = instance[keyPath: storageKeyPath]
if let value = wrapper.value {
return value
} else {
guard let data = instance[keyPath: wrapper.keyPath] else { return wrapper.fallback }
do {
let value = try decoder.decode(Box.self, from: data)
wrapper.value = value.value
wrapper.observation = instance.observe(wrapper.keyPath, changeHandler: { instance, _ in
var wrapper = instance[keyPath: storageKeyPath]
if wrapper.skipClearingOnNextUpdate {
wrapper.skipClearingOnNextUpdate = false
} else {
wrapper.removeCachedValue()
}
instance[keyPath: storageKeyPath] = wrapper
})
var wrapper = instance[keyPath: storageKeyPath]
if let value = wrapper.value {
return value
} else {
guard let data = instance[keyPath: wrapper.keyPath] else { return wrapper.fallback }
do {
let value = try decoder.decode(Box.self, from: data)
wrapper.value = value.value
wrapper.observation = instance.observe(wrapper.keyPath, changeHandler: { instance, _ in
var wrapper = instance[keyPath: storageKeyPath]
if wrapper.skipClearingOnNextUpdate {
wrapper.skipClearingOnNextUpdate = false
} else {
wrapper.removeCachedValue()
}
instance[keyPath: storageKeyPath] = wrapper
return value.value
} catch {
return wrapper.fallback
}
})
instance[keyPath: storageKeyPath] = wrapper
return value.value
} catch {
return wrapper.fallback
}
}
}
set {
instance.performOnContext {
var wrapper = instance[keyPath: storageKeyPath]
wrapper.value = newValue
wrapper.skipClearingOnNextUpdate = true
instance[keyPath: storageKeyPath] = wrapper
let newData = try! encoder.encode(Box(value: newValue))
instance[keyPath: wrapper.keyPath] = newData
}
var wrapper = instance[keyPath: storageKeyPath]
wrapper.value = newValue
wrapper.skipClearingOnNextUpdate = true
instance[keyPath: storageKeyPath] = wrapper
let newData = try! encoder.encode(Box(value: newValue))
instance[keyPath: wrapper.keyPath] = newData
}
}
@ -78,16 +74,6 @@ public struct LazilyDecoding<Enclosing: NSManagedObject, Value: Codable> {
}
extension NSManagedObject {
fileprivate func performOnContext<V>(_ f: () -> V) -> V {
if let managedObjectContext {
managedObjectContext.performAndWait(f)
} else {
f()
}
}
}
extension LazilyDecoding {
init<T>(arrayFrom keyPath: ReferenceWritableKeyPath<Enclosing, Data?>) where Value == [T] {
self.init(from: keyPath, fallback: [])