This commit is contained in:
John Estropia
2026-07-24 11:51:36 +09:00
parent 1ea9ad7c4a
commit 13093d72d4
51 changed files with 1083 additions and 243 deletions
+43 -4
View File
@@ -80,19 +80,21 @@ public nonisolated final class AsynchronousDataTransaction: BaseDataTransaction
}
/**
Returns an editable proxy of a specified `NSManagedObject` or `CoreStoreObject`.
Returns an editable proxy of the object with the specified `DynamicObjectID`.
- parameter persistentID: the `DynamicObjectID` pertaining ot the `NSManagedObject` or `CoreStoreObject` type to be edited
- parameter into: an `Into` clause specifying the entity type
- parameter persistentID: the `DynamicObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public override func edit<O: DynamicObject>(
public override func edit<O>(
_ persistentID: DynamicObjectID<O>?
) -> O? {
Internals.assert(
!self.isCommitted,
"Attempted to update an entity for \(Internals.typeName(persistentID)) from an already committed \(Internals.typeName(self))."
"Attempted to update an entity of type \(Internals.typeName(persistentID)) from an already committed \(Internals.typeName(self))."
)
return super.edit(persistentID)
}
@@ -114,6 +116,26 @@ public nonisolated final class AsynchronousDataTransaction: BaseDataTransaction
return super.edit(object)
}
/**
Returns an editable proxy of the object with the specified `DynamicObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter persistentID: the `DynamicObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public override func edit<O>(
_ into: Into<O>,
_ persistentID: DynamicObjectID<O>
) -> O? {
Internals.assert(
!self.isCommitted,
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))."
)
return super.edit(into, persistentID)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
@@ -133,6 +155,23 @@ public nonisolated final class AsynchronousDataTransaction: BaseDataTransaction
return super.edit(into, objectID)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
- parameter objectIDs: the `NSManagedObjectID`s of the objects to delete
*/
public override func delete<O: DynamicObject, S: Sequence>(
persistentIDs: S
) where S.Iterator.Element == DynamicObjectID<O> {
Internals.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(Internals.typeName(self))."
)
super.delete(persistentIDs: persistentIDs)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
+6 -6
View File
@@ -42,7 +42,7 @@ extension BaseDataTransaction {
public func importObject<O: ImportableObject>(
_ into: Into<O>,
source: O.ImportSource
) throws(any Swift.Error) -> O? {
) throws(any Swift::Error) -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
@@ -73,7 +73,7 @@ extension BaseDataTransaction {
public func importObject<O: ImportableObject>(
_ object: O,
source: O.ImportSource
) throws(any Swift.Error) {
) throws(any Swift::Error) {
Internals.assert(
self.isRunningInAllowedQueue(),
@@ -102,7 +102,7 @@ extension BaseDataTransaction {
public func importObjects<O: ImportableObject, S: Sequence>(
_ into: Into<O>,
sourceArray: S
) throws(any Swift.Error) -> [O] where S.Iterator.Element == O.ImportSource {
) throws(any Swift::Error) -> [O] where S.Iterator.Element == O.ImportSource {
Internals.assert(
self.isRunningInAllowedQueue(),
@@ -139,7 +139,7 @@ extension BaseDataTransaction {
public func importUniqueObject<O: ImportableUniqueObject>(
_ into: Into<O>,
source: O.ImportSource
) throws(any Swift.Error) -> O? {
) throws(any Swift::Error) -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
@@ -194,8 +194,8 @@ extension BaseDataTransaction {
sourceArray: S,
preProcess: @escaping (
_ mapping: [O.UniqueIDType: O.ImportSource]
) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) throws(any Swift.Error) -> [O] where S.Iterator.Element == O.ImportSource {
) throws(any Swift::Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) throws(any Swift::Error) -> [O] where S.Iterator.Element == O.ImportSource {
Internals.assert(
self.isRunningInAllowedQueue(),
+45 -1
View File
@@ -121,7 +121,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter persistentID: the `DynamicObjectID` pertaining ot the `NSManagedObject` or `CoreStoreObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public func edit<O: DynamicObject>(
public func edit<O>(
_ persistentID: DynamicObjectID<O>?
) -> O? {
@@ -157,6 +157,30 @@ public /*abstract*/ class BaseDataTransaction {
return self.context.fetchExisting(object)
}
/**
Returns an editable proxy of the object with the specified `DynamicObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter persistentID: the `DynamicObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public func edit<O>(
_ into: Into<O>,
_ persistentID: DynamicObjectID<O>
) -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) outside its designated queue."
)
Internals.assert(
into.inferStoreIfPossible
|| (into.configuration ?? DataStack.defaultConfigurationName) == persistentID.managedObjectID.persistentStore?.configurationName,
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) but the specified persistent store do not match the `NSManagedObjectID`."
)
return self.fetchExisting(persistentID)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
@@ -180,6 +204,26 @@ public /*abstract*/ class BaseDataTransaction {
)
return self.fetchExisting(objectID)
}
/**
Deletes the objects with the specified `DynamicObjectID`s.
- parameter persistentIDs: the `DynamicObjectID`s of the objects to delete
*/
public func delete<O: DynamicObject, S: Sequence>(
persistentIDs: S
) where S.Iterator.Element == DynamicObjectID<O> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete an entity outside its designated queue."
)
let context = self.context
persistentIDs.forEach {
context.fetchExisting($0).map({ context.delete($0.cs_toRaw()) })
}
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
+3 -3
View File
@@ -32,7 +32,7 @@ import Foundation
/**
All errors thrown from CoreStore are expressed in `CoreStoreError` enum values.
*/
public enum CoreStoreError: Error, CustomNSError, Hashable, Sendable {
public enum CoreStoreError: Swift::Error, CustomNSError, Hashable, Sendable {
/**
A failure occured because of an unknown error.
@@ -67,7 +67,7 @@ public enum CoreStoreError: Error, CustomNSError, Hashable, Sendable {
/**
The transaction was terminated by a user-thrown `Error`.
*/
case userError(error: Error)
case userError(error: Swift::Error)
/**
The transaction was cancelled by the user.
@@ -82,7 +82,7 @@ public enum CoreStoreError: Error, CustomNSError, Hashable, Sendable {
/**
Casts any `Error` to a known `CoreStoreError`, or wraps it in `CoreStoreError.internalError(NSError:)`.
*/
public init(_ error: Error?) {
public init(_ error: Swift::Error?) {
guard let error = error else {
+4 -4
View File
@@ -108,7 +108,7 @@ public final class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider
public typealias Transformer = @Sendable (
_ sourceObject: UnsafeSourceObject,
_ createDestinationObject: () -> UnsafeDestinationObject
) throws(any Swift.Error) -> Void
) throws(any Swift::Error) -> Void
/**
The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight).
@@ -116,7 +116,7 @@ public final class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider
public static func inferredTransformation(
_ sourceObject: UnsafeSourceObject,
_ createDestinationObject: () -> UnsafeDestinationObject
) throws(any Swift.Error) {
) throws(any Swift::Error) {
let destinationObject = createDestinationObject()
destinationObject.enumerateAttributes { (attribute, sourceAttribute) in
@@ -556,7 +556,7 @@ public final class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider
forSource sInstance: NSManagedObject,
in mapping: NSEntityMapping,
manager: NSMigrationManager
) throws(any Swift.Error) {
) throws(any Swift::Error) {
let userInfo = mapping.userInfo!
let transformer = userInfo[CustomEntityMigrationPolicy.UserInfoKey.transformer]! as! CustomMapping.Transformer
@@ -588,7 +588,7 @@ public final class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider
forDestination dInstance: NSManagedObject,
in mapping: NSEntityMapping,
manager: NSMigrationManager
) throws(any Swift.Error) {
) throws(any Swift::Error) {
try super.createRelationships(forDestination: dInstance, in: mapping, manager: manager)
}
+9 -9
View File
@@ -85,7 +85,7 @@ extension DataStack.AsyncNamespace {
*/
public func addStorage<T: StorageInterface>(
_ storage: T
) async throws(any Swift.Error) -> T {
) async throws(any Swift::Error) -> T {
return try await Internals.withCheckedThrowingContinuation { continuation in
@@ -118,7 +118,7 @@ extension DataStack.AsyncNamespace {
*/
public func addStorage<T>(
_ storage: T
) -> AsyncThrowingStream<MigrationProgress<T>, any Swift.Error> {
) -> AsyncThrowingStream<MigrationProgress<T>, any Swift::Error> {
return .init(
bufferingPolicy: .unbounded,
@@ -184,7 +184,7 @@ extension DataStack.AsyncNamespace {
public func importObject<O: DynamicObject & ImportableObject>(
_ into: Into<O>,
source: O.ImportSource
) async throws(any Swift.Error) -> O? {
) async throws(any Swift::Error) -> O? {
return try await Internals.withCheckedThrowingContinuation { continuation in
@@ -226,7 +226,7 @@ extension DataStack.AsyncNamespace {
public func importObject<O: DynamicObject & ImportableObject>(
_ object: O,
source: O.ImportSource
) async throws(any Swift.Error) -> O? {
) async throws(any Swift::Error) -> O? {
nonisolated(unsafe) let object = object
return try await Internals.withCheckedThrowingContinuation { continuation in
@@ -274,7 +274,7 @@ extension DataStack.AsyncNamespace {
public func importUniqueObject<O: DynamicObject & ImportableUniqueObject>(
_ into: Into<O>,
source: O.ImportSource
) async throws(any Swift.Error) -> O? {
) async throws(any Swift::Error) -> O? {
return try await Internals.withCheckedThrowingContinuation { continuation in
@@ -324,8 +324,8 @@ extension DataStack.AsyncNamespace {
sourceArray: S,
preProcess: @escaping @Sendable (
_ mapping: [O.UniqueIDType: O.ImportSource]
) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) async throws(any Swift.Error) -> [O]
) throws(any Swift::Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) async throws(any Swift::Error) -> [O]
where S.Iterator.Element == O.ImportSource {
return try await Internals.withCheckedThrowingContinuation { continuation in
@@ -374,8 +374,8 @@ extension DataStack.AsyncNamespace {
- throws: A `CoreStoreError` value indicating the failure reason
*/
public func perform<Output: Sendable>(
_ asynchronous: @escaping @Sendable (AsynchronousDataTransaction) throws(any Swift.Error) -> Output
) async throws(any Swift.Error) -> Output {
_ asynchronous: @escaping @Sendable (AsynchronousDataTransaction) throws(any Swift::Error) -> Output
) async throws(any Swift::Error) -> Output {
return try await Internals.withCheckedThrowingContinuation { continuation in
+2 -2
View File
@@ -326,7 +326,7 @@ extension DataStack.ReactiveNamespace {
sourceArray: S,
preProcess: @escaping @Sendable (
_ mapping: [O.UniqueIDType: O.ImportSource]
) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) throws(any Swift::Error) -> [O.UniqueIDType: O.ImportSource] = { $0 }
) -> Future<[O], CoreStoreError> where S.Iterator.Element == O.ImportSource {
return .init { (promise) in
@@ -379,7 +379,7 @@ extension DataStack.ReactiveNamespace {
public func perform<Output: Sendable>(
_ asynchronous: @escaping @Sendable (
_ transaction: AsynchronousDataTransaction
) throws(any Swift.Error) -> Output
) throws(any Swift::Error) -> Output
) -> Future<Output, CoreStoreError> {
return .init { (promise) in
+3 -3
View File
@@ -41,7 +41,7 @@ extension DataStack {
public func perform<T: Sendable>(
asynchronous task: @escaping @Sendable (
_ transaction: AsynchronousDataTransaction
) throws(any Swift.Error) -> T,
) throws(any Swift::Error) -> T,
sourceIdentifier: (any Sendable)? = nil,
completion: @escaping @MainActor @Sendable (AsynchronousDataTransaction.Result<T>) -> Void
) {
@@ -65,7 +65,7 @@ extension DataStack {
public func perform<T>(
asynchronous task: @escaping @Sendable (
_ transaction: AsynchronousDataTransaction
) throws(any Swift.Error) -> T,
) throws(any Swift::Error) -> T,
sourceIdentifier: (any Sendable)? = nil,
success: @escaping @MainActor @Sendable (sending T) -> Void,
failure: @escaping @MainActor @Sendable (CoreStoreError) -> Void
@@ -123,7 +123,7 @@ extension DataStack {
public func perform<T>(
synchronous task: (
_ transaction: SynchronousDataTransaction
) throws(any Swift.Error) -> T,
) throws(any Swift::Error) -> T,
waitForAllObservers: Bool = true,
sourceIdentifier: (any Sendable)? = nil
) throws(CoreStoreError) -> T {
+1 -1
View File
@@ -535,7 +535,7 @@ public final class DataStack: Equatable, Sendable {
_ storage: StorageInterface,
finalURL: URL?,
finalStoreOptions: [AnyHashable: Any]?
) throws(any Swift.Error) -> NSPersistentStore {
) throws(any Swift::Error) -> NSPersistentStore {
let persistentStore = try self.coordinator.addPersistentStore(
ofType: type(of: storage).storeType,
@@ -128,7 +128,7 @@ extension DiffableDataSource {
itemForRepresentedObjectAt indexPath: IndexPath
) -> NSCollectionViewItem {
guard let objectID = self.itemID(for: indexPath) else {
guard let objectID: NSManagedObjectID = self.itemID(for: indexPath) else {
Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) already removed from list")
}
+1 -1
View File
@@ -107,7 +107,7 @@ extension DispatchQueue {
@nonobjc @inline(__always)
internal func cs_barrierSync<T>(
_ closure: () throws(any Swift.Error) -> T
_ closure: () throws(any Swift::Error) -> T
) rethrows -> T {
return try self.sync(flags: .barrier) { try autoreleasepool(invoking: closure) }
+6 -2
View File
@@ -142,7 +142,9 @@ extension NSManagedObject: DynamicObject {
}
@_spi(Internals)
public class func cs_fromRaw(object: NSManagedObject) -> Self {
public class func cs_fromRaw(
object: NSManagedObject
) -> Self {
#if swift(>=5.9)
return unsafeDowncast(object, to: self)
@@ -309,7 +311,9 @@ extension CoreStoreObject {
}
@_spi(Internals)
public class func cs_fromRaw(object: NSManagedObject) -> Self {
public class func cs_fromRaw(
object: NSManagedObject
) -> Self {
if let coreStoreObject = object.coreStoreObject {
+1 -1
View File
@@ -80,7 +80,7 @@ public protocol ImportableObject: DynamicObject {
func didInsert(
from source: ImportSource,
in transaction: BaseDataTransaction
) throws(any Swift.Error)
) throws(any Swift::Error)
}
+4 -4
View File
@@ -105,7 +105,7 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable {
static func uniqueID(
from source: ImportSource,
in transaction: BaseDataTransaction
) throws(any Swift.Error) -> UniqueIDType?
) throws(any Swift::Error) -> UniqueIDType?
/**
Implements the actual importing of data from `source`. This method is called just after the object is created and assigned its unique ID as returned from `uniqueID(from:in:)`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled. The default implementation simply calls `update(from:in:)`.
@@ -116,7 +116,7 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable {
func didInsert(
from source: ImportSource,
in transaction: BaseDataTransaction
) throws(any Swift.Error)
) throws(any Swift::Error)
/**
Implements the actual importing of data from `source`. This method is called just after the existing object is fetched using its unique ID. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled.
@@ -127,7 +127,7 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable {
func update(
from source: ImportSource,
in transaction: BaseDataTransaction
) throws(any Swift.Error)
) throws(any Swift::Error)
}
@@ -180,7 +180,7 @@ extension ImportableUniqueObject {
public func didInsert(
from source: Self.ImportSource,
in transaction: BaseDataTransaction
) throws(any Swift.Error) {
) throws(any Swift::Error) {
try self.update(from: source, in: transaction)
}
@@ -77,7 +77,7 @@ extension Internals {
}
@nonobjc
internal func performFetchFromSpecifiedStores() throws(any Swift.Error) {
internal func performFetchFromSpecifiedStores() throws(any Swift::Error) {
try self.reapplyAffectedStores(self.typedFetchRequest, self.managedObjectContext)
try self.performFetch()
@@ -106,6 +106,6 @@ extension Internals {
private let reapplyAffectedStores: (
_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>,
_ context: NSManagedObjectContext
) throws(any Swift.Error) -> Void
) throws(any Swift::Error) -> Void
}
}
+2 -2
View File
@@ -46,7 +46,7 @@ extension Internals {
borrowing func withLock<Result, E>(
_ body: (inout sending Value) throws(E) -> sending Result
) throws(E) -> sending Result
where E: Error, Result: ~Copyable {
where E: Swift::Error, Result: ~Copyable {
let storage = self.storage
storage.lock()
@@ -60,7 +60,7 @@ extension Internals {
borrowing func withLockUnchecked<Result, E>(
_ body: (inout sending Value) throws(E) -> Result
) throws(E) -> sending Result
where E: Error {
where E: Swift::Error {
let storage = self.storage
storage.lock()
+4 -4
View File
@@ -133,8 +133,8 @@ internal enum Internals {
@inline(__always)
internal static func autoreleasepool<T>(
_ closure: () throws(any Swift.Error) -> T
) throws(any Swift.Error) -> T {
_ closure: () throws(any Swift::Error) -> T
) throws(any Swift::Error) -> T {
return try ObjectiveC.autoreleasepool(invoking: closure)
}
@@ -142,8 +142,8 @@ internal enum Internals {
@inline(__always)
internal static func withCheckedThrowingContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, any Swift.Error>) -> Void
) async throws(any Swift.Error) -> sending T {
_ body: (CheckedContinuation<T, any Swift::Error>) -> Void
) async throws(any Swift::Error) -> sending T {
return try await _Concurrency.withCheckedThrowingContinuation(
function: function,
+3 -3
View File
@@ -189,7 +189,7 @@ public final class ListPublisher<O: DynamicObject>: Hashable {
public func refetch<B: FetchChainableBuilderType>(
_ clauseChain: B,
sourceIdentifier: (any Sendable)? = nil
) throws(any Swift.Error) where B.ObjectType == O {
) throws(any Swift::Error) where B.ObjectType == O {
try self.refetch(
from: clauseChain.from,
@@ -218,7 +218,7 @@ public final class ListPublisher<O: DynamicObject>: Hashable {
public func refetch<B: SectionMonitorBuilderType>(
_ clauseChain: B,
sourceIdentifier: (any Sendable)? = nil
) throws(any Swift.Error) where B.ObjectType == O {
) throws(any Swift::Error) where B.ObjectType == O {
try self.refetch(
from: clauseChain.from,
@@ -347,7 +347,7 @@ public final class ListPublisher<O: DynamicObject>: Hashable {
sectionBy: SectionBy<O>?,
applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void,
sourceIdentifier: (any Sendable)?
) throws(any Swift.Error) {
) throws(any Swift::Error) {
let (newFetchedResultsController, newFetchedResultsControllerDelegate) = Self.recreateFetchedResultsController(
context: self.fetchedResultsController.managedObjectContext,
+35 -14
View File
@@ -35,7 +35,7 @@ import SwiftUI
A property wrapper type that can read `ListPublisher` changes.
*/
@propertyWrapper
public struct ListState<O: DynamicObject>: DynamicProperty {
public struct ListState<O: DynamicObject>: @MainActor DynamicProperty {
// MARK: Public
@@ -70,6 +70,7 @@ public struct ListState<O: DynamicObject>: DynamicProperty {
_ listPublisher: ListPublisher<O>
) {
self.sourceListPublisher = listPublisher
self._observer = .init(wrappedValue: .init(listPublisher: listPublisher))
}
@@ -338,9 +339,11 @@ public struct ListState<O: DynamicObject>: DynamicProperty {
// MARK: DynamicProperty
@MainActor
public mutating func update() {
self._observer.update()
self.observer.rebind(to: self.sourceListPublisher)
}
@@ -349,13 +352,15 @@ public struct ListState<O: DynamicObject>: DynamicProperty {
@State
private var observer: Observer
private let sourceListPublisher: ListPublisher<O>
// MARK: - Observer
@MainActor
private final class Observer: Observation.Observable {
let listPublisher: ListPublisher<O>
private(set) var listPublisher: ListPublisher<O>
nonisolated var items: ListSnapshot<O> {
@@ -377,8 +382,35 @@ public struct ListState<O: DynamicObject>: DynamicProperty {
self.listPublisher = listPublisher
self.current = .init(listPublisher.snapshot)
self.attachObserver()
}
isolated deinit {
listPublisher.addObserver(self) { [weak self] (listPublisher) in
self.listPublisher.removeObserver(self)
}
func rebind(to listPublisher: ListPublisher<O>) {
guard self.listPublisher !== listPublisher else {
return
}
self.listPublisher.removeObserver(self)
self.listPublisher = listPublisher
self.items = listPublisher.snapshot
self.attachObserver()
}
// MARK: Private
private let registrar = ObservationRegistrar()
private let current: Internals.Mutex<ListSnapshot<O>>
private func attachObserver() {
self.listPublisher.addObserver(self) { [weak self] listPublisher in
guard let self = self else {
@@ -387,17 +419,6 @@ public struct ListState<O: DynamicObject>: DynamicProperty {
self.items = listPublisher.snapshot
}
}
isolated deinit {
self.listPublisher.removeObserver(self)
}
// MARK: Private
private let registrar = ObservationRegistrar()
private let current: Internals.Mutex<ListSnapshot<O>>
}
}
+4 -4
View File
@@ -106,7 +106,7 @@ extension NSManagedObject {
@nonobjc @inline(__always)
public func getValue<T>(
forKvcKey kvcKey: KeyPathString,
didGetValue: (Any?) throws(any Swift.Error) -> T
didGetValue: (Any?) throws(any Swift::Error) -> T
) rethrows -> T {
self.willAccessValue(forKey: kvcKey)
@@ -128,8 +128,8 @@ extension NSManagedObject {
@nonobjc @inline(__always)
public func getValue<T>(
forKvcKey kvcKey: KeyPathString,
willGetValue: () throws(any Swift.Error) -> Void,
didGetValue: (Any?) throws(any Swift.Error) -> T
willGetValue: () throws(any Swift::Error) -> Void,
didGetValue: (Any?) throws(any Swift::Error) -> T
) rethrows -> T {
self.willAccessValue(forKey: kvcKey)
@@ -196,7 +196,7 @@ extension NSManagedObject {
public func setValue<T>(
_ value: T,
forKvcKey KVCKey: KeyPathString,
willSetValue: (T) throws(any Swift.Error) -> Any?,
willSetValue: (T) throws(any Swift::Error) -> Any?,
didSetValue: (Any?) -> Void = { _ in }
) rethrows {
+10 -2
View File
@@ -76,6 +76,14 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource {
}
}
@nonobjc
public func fetchExisting<O: DynamicObject>(
_ persistentID: DynamicObjectID<O>
) -> O? {
return self.fetchExisting(persistentID.managedObjectID)
}
@nonobjc
public func fetchExisting<O: DynamicObject>(
_ objectID: NSManagedObjectID
@@ -102,10 +110,10 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource {
@nonobjc
public func fetchExisting<O: DynamicObject, S: Sequence>(
_ objectIDs: S
_ persistentIDs: S
) -> [O] where S.Iterator.Element == DynamicObjectID<O> {
return objectIDs.compactMap({ self.fetchExisting($0.managedObjectID) })
return persistentIDs.compactMap({ self.fetchExisting($0.managedObjectID) })
}
@nonobjc
@@ -49,7 +49,7 @@ extension NSPersistentStoreCoordinator {
@nonobjc
internal func performSynchronously<T>(
_ closure: @Sendable () throws(any Swift.Error) -> T
_ closure: @Sendable () throws(any Swift::Error) -> T
) throws(CoreStoreError) -> T {
do {
+16 -9
View File
@@ -72,32 +72,36 @@ public final class ObjectMonitor<O: DynamicObject>: Hashable, ObjectRepresentati
- parameter observer: an `ObjectObserver` to send change notifications to
*/
@MainActor
public func addObserver<U: ObjectObserver & Sendable>(_ observer: U) where U.ObjectEntityType == O {
public func addObserver<U: ObjectObserver & Sendable>(_ observer: U)
where U.ObjectEntityType == O {
self.unregisterObserver(observer)
self.registerObserver(
observer,
willChangeObject: { (observer, monitor, object) in
nonisolated(unsafe) let sending = object
observer.objectMonitor(
monitor,
willUpdateObject: object,
willUpdateObject: sending,
sourceIdentifier: monitor.context.saveMetadata?.sourceIdentifier
)
},
didDeleteObject: { (observer, monitor, object) in
nonisolated(unsafe) let sending = object
observer.objectMonitor(
monitor,
didDeleteObject: object,
didDeleteObject: sending,
sourceIdentifier: monitor.context.saveMetadata?.sourceIdentifier
)
},
didUpdateObject: { (observer, monitor, object, changedPersistentKeys) in
nonisolated(unsafe) let sending = object
observer.objectMonitor(
monitor,
didUpdateObject: object,
didUpdateObject: sending,
changedPersistentKeys: changedPersistentKeys,
sourceIdentifier: monitor.context.saveMetadata?.sourceIdentifier
)
@@ -113,7 +117,8 @@ public final class ObjectMonitor<O: DynamicObject>: Hashable, ObjectRepresentati
- parameter observer: an `ObjectObserver` to unregister notifications to
*/
@MainActor
public func removeObserver<U: ObjectObserver>(_ observer: U) where U.ObjectEntityType == O {
public func removeObserver<U: ObjectObserver>(_ observer: U)
where U.ObjectEntityType == O {
self.unregisterObserver(observer)
}
@@ -412,11 +417,13 @@ public final class ObjectMonitor<O: DynamicObject>: Hashable, ObjectRepresentati
object: self,
closure: { [weak self] (note) in
guard let self = self,
guard
let self = self,
let userInfo = note.userInfo,
let object = userInfo[String(describing: NSManagedObject.self)] as! NSManagedObject? else {
return
let object = userInfo[String(describing: NSManagedObject.self)] as! NSManagedObject?
else {
return
}
callback(self, O.cs_fromRaw(object: object))
}
+18 -18
View File
@@ -53,8 +53,8 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
willUpdateObject object: ObjectEntityType,
sourceIdentifier: Any?
willUpdateObject object: sending ObjectEntityType,
sourceIdentifier: (any Sendable)?
)
/**
@@ -66,7 +66,7 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
willUpdateObject object: ObjectEntityType
willUpdateObject object: sending ObjectEntityType
)
/**
@@ -80,9 +80,9 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didUpdateObject object: ObjectEntityType,
didUpdateObject object: sending ObjectEntityType,
changedPersistentKeys: Set<KeyPathString>,
sourceIdentifier: Any?
sourceIdentifier: (any Sendable)?
)
/**
@@ -95,7 +95,7 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didUpdateObject object: ObjectEntityType,
didUpdateObject object: sending ObjectEntityType,
changedPersistentKeys: Set<KeyPathString>
)
@@ -109,8 +109,8 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didDeleteObject object: ObjectEntityType,
sourceIdentifier: Any?
didDeleteObject object: sending ObjectEntityType,
sourceIdentifier: (any Sendable)?
)
/**
@@ -122,7 +122,7 @@ public protocol ObjectObserver: AnyObject, Sendable {
*/
func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didDeleteObject object: ObjectEntityType
didDeleteObject object: sending ObjectEntityType
)
}
@@ -133,8 +133,8 @@ extension ObjectObserver {
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
willUpdateObject object: ObjectEntityType,
sourceIdentifier: Any?
willUpdateObject object: sending ObjectEntityType,
sourceIdentifier: (any Sendable)?
) {
self.objectMonitor(
@@ -145,14 +145,14 @@ extension ObjectObserver {
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
willUpdateObject object: ObjectEntityType
willUpdateObject object: sending ObjectEntityType
) {}
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didUpdateObject object: ObjectEntityType,
didUpdateObject object: sending ObjectEntityType,
changedPersistentKeys: Set<KeyPathString>,
sourceIdentifier: Any?
sourceIdentifier: (any Sendable)?
) {
self.objectMonitor(
@@ -164,14 +164,14 @@ extension ObjectObserver {
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didUpdateObject object: ObjectEntityType,
didUpdateObject object: sending ObjectEntityType,
changedPersistentKeys: Set<KeyPathString>
) {}
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didDeleteObject object: ObjectEntityType,
sourceIdentifier: Any?
didDeleteObject object: sending ObjectEntityType,
sourceIdentifier: (any Sendable)?
) {
self.objectMonitor(
@@ -182,6 +182,6 @@ extension ObjectObserver {
public func objectMonitor(
_ monitor: ObjectMonitor<ObjectEntityType>,
didDeleteObject object: ObjectEntityType
didDeleteObject object: sending ObjectEntityType
) {}
}
+1 -1
View File
@@ -106,7 +106,7 @@ public struct ObjectReader<Object: DynamicObject, Content: View, Placeholder: Vi
keyPath: KeyPath<ObjectSnapshot<Object>, Value>,
@ViewBuilder content: @escaping (Value) -> Content,
@ViewBuilder placeholder: @escaping () -> Placeholder
) where Placeholder == EmptyView {
) {
self._object = .init(objectPublisher)
self.content = {
+40 -19
View File
@@ -35,7 +35,7 @@ import SwiftUI
A property wrapper type that can read `ObjectPublisher` changes.
*/
@propertyWrapper
public struct ObjectState<O: DynamicObject>: DynamicProperty {
public struct ObjectState<O: DynamicObject>: @MainActor DynamicProperty {
// MARK: Public
@@ -65,6 +65,7 @@ public struct ObjectState<O: DynamicObject>: DynamicProperty {
@MainActor
public init(_ objectPublisher: ObjectPublisher<O>?) {
self.sourceObjectPublisher = objectPublisher
self._observer = .init(wrappedValue: .init(objectPublisher: objectPublisher))
}
@@ -86,9 +87,11 @@ public struct ObjectState<O: DynamicObject>: DynamicProperty {
// MARK: DynamicProperty
@MainActor
public mutating func update() {
self._observer.update()
self.observer.rebind(to: self.sourceObjectPublisher)
}
@@ -97,13 +100,15 @@ public struct ObjectState<O: DynamicObject>: DynamicProperty {
@State
private var observer: Observer
private let sourceObjectPublisher: ObjectPublisher<O>?
// MARK: - Observer
@MainActor
private final class Observer: Observation.Observable {
let objectPublisher: ObjectPublisher<O>?
private(set) var objectPublisher: ObjectPublisher<O>?
nonisolated var item: ObjectSnapshot<O>? {
@@ -122,21 +127,28 @@ public struct ObjectState<O: DynamicObject>: DynamicProperty {
}
init(objectPublisher: ObjectPublisher<O>?) {
guard
let dataStack = objectPublisher?.cs_dataStack(),
let objectPublisher = objectPublisher?.asPublisher(in: dataStack)
else {
self.objectPublisher = nil
self.current = .init(nil)
self.objectPublisher = nil
self.current = .init(nil)
self.rebind(to: objectPublisher)
}
isolated deinit {
self.objectPublisher?.removeObserver(self)
}
func rebind(to objectPublisher: ObjectPublisher<O>?) {
let objectPublisher = Self.canonicalPublisher(for: objectPublisher)
guard self.objectPublisher != objectPublisher else {
return
}
self.objectPublisher?.removeObserver(self)
self.objectPublisher = objectPublisher
self.current = .init(objectPublisher.snapshot)
objectPublisher.addObserver(self) { [weak self] (objectPublisher) in
self.item = objectPublisher?.snapshot
objectPublisher?.addObserver(self) { [weak self] objectPublisher in
guard let self = self else {
@@ -146,16 +158,25 @@ public struct ObjectState<O: DynamicObject>: DynamicProperty {
}
}
isolated deinit {
self.objectPublisher?.removeObserver(self)
}
// MARK: Private
private let registrar = ObservationRegistrar()
private let current: Internals.Mutex<ObjectSnapshot<O>?>
private static func canonicalPublisher(
for objectPublisher: ObjectPublisher<O>?
) -> ObjectPublisher<O>? {
guard
let objectPublisher = objectPublisher,
let dataStack = objectPublisher.cs_dataStack()
else {
return nil
}
return objectPublisher.asPublisher(in: dataStack)
}
}
}
+3 -3
View File
@@ -236,7 +236,7 @@ public final class SQLiteStore: LocalStorage {
@_spi(Internals)
public func cs_finalizeStorageAndWait(
soureModelHint: NSManagedObjectModel
) throws(any Swift.Error) {
) throws(any Swift::Error) {
_ = try withExtendedLifetime(NSPersistentStoreCoordinator(managedObjectModel: soureModelHint)) { (coordinator: NSPersistentStoreCoordinator) in
@@ -259,12 +259,12 @@ public final class SQLiteStore: LocalStorage {
public func cs_eraseStorageAndWait(
metadata: [String: Any],
soureModelHint: NSManagedObjectModel?
) throws(any Swift.Error) {
) throws(any Swift::Error) {
func deleteFiles(
storeURL: URL,
extraFiles: [String] = []
) throws(any Swift.Error) {
) throws(any Swift::Error) {
let fileManager = FileManager.default
let extraFiles: [String] = [
+2 -2
View File
@@ -151,7 +151,7 @@ public protocol LocalStorage: StorageInterface {
@_spi(Internals)
func cs_finalizeStorageAndWait(
soureModelHint: NSManagedObjectModel
) throws(any Swift.Error)
) throws(any Swift::Error)
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. **Do not call directly!** The `sourceModel` argument is a hint for the existing store's model version. Implementers can use the `sourceModel` to perform necessary store operations. (SQLite stores for example, can convert WAL journaling mode to DELETE before deleting)
@@ -160,7 +160,7 @@ public protocol LocalStorage: StorageInterface {
func cs_eraseStorageAndWait(
metadata: [String: Any],
soureModelHint: NSManagedObjectModel?
) throws(any Swift.Error)
) throws(any Swift::Error)
}
extension LocalStorage {
+37
View File
@@ -103,6 +103,26 @@ public nonisolated final class SynchronousDataTransaction: BaseDataTransaction {
return super.edit(object)
}
/**
Returns an editable proxy of the object with the specified `DynamicObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter persistentID: the `DynamicObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public override func edit<O>(
_ into: Into<O>,
_ persistentID: DynamicObjectID<O>
) -> O? {
Internals.assert(
!self.isCommitted,
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))."
)
return super.edit(into, persistentID)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
@@ -122,6 +142,23 @@ public nonisolated final class SynchronousDataTransaction: BaseDataTransaction {
return super.edit(into, objectID)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
- parameter objectIDs: the `NSManagedObjectID`s of the objects to delete
*/
public override func delete<O: DynamicObject, S: Sequence>(
persistentIDs: S
) where S.Iterator.Element == DynamicObjectID<O> {
Internals.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(Internals.typeName(self))."
)
super.delete(persistentIDs: persistentIDs)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
+1 -1
View File
@@ -114,7 +114,7 @@ public final class UnsafeDataTransaction: BaseDataTransaction, @unchecked Sendab
- throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors)
*/
public func flush(
closure: () throws(any Swift.Error) -> Void
closure: () throws(any Swift::Error) -> Void
) rethrows {
try closure()