WIP: Xcode 8 beta 6

This commit is contained in:
John Estropia
2016-09-06 09:57:28 +09:00
parent e9be711d4c
commit 0ba63c6e72
78 changed files with 472 additions and 450 deletions
-1
View File
@@ -1 +0,0 @@
github "JohnEstropia/GCDKit" == 1.2.6
+1 -3
View File
@@ -18,6 +18,4 @@ Pod::Spec.new do |s|
s.requires_arc = true s.requires_arc = true
s.pod_target_xcconfig = { 'OTHER_SWIFT_FLAGS' => '-D USE_FRAMEWORKS', s.pod_target_xcconfig = { 'OTHER_SWIFT_FLAGS' => '-D USE_FRAMEWORKS',
'GCC_PREPROCESSOR_DEFINITIONS' => 'USE_FRAMEWORKS=1' } 'GCC_PREPROCESSOR_DEFINITIONS' => 'USE_FRAMEWORKS=1' }
end
s.dependency "GCDKit", "1.2.6"
end
+12 -8
View File
@@ -193,6 +193,10 @@
B52DD1C91BE1F94600949AFE /* NSManagedObjectContext+Transaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E84F331AFF85470064E85B /* NSManagedObjectContext+Transaction.swift */; }; B52DD1C91BE1F94600949AFE /* NSManagedObjectContext+Transaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E84F331AFF85470064E85B /* NSManagedObjectContext+Transaction.swift */; };
B52DD1CA1BE1F94600949AFE /* NSManagedObjectModel+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51BE0691B47FC4B0069F532 /* NSManagedObjectModel+Setup.swift */; }; B52DD1CA1BE1F94600949AFE /* NSManagedObjectModel+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51BE0691B47FC4B0069F532 /* NSManagedObjectModel+Setup.swift */; };
B52DD1CB1BE1F94600949AFE /* WeakObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E84F2D1AFF849C0064E85B /* WeakObject.swift */; }; B52DD1CB1BE1F94600949AFE /* WeakObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E84F2D1AFF849C0064E85B /* WeakObject.swift */; };
B533C4DB1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */; };
B533C4DC1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */; };
B533C4DD1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */; };
B533C4DE1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */; };
B538BA771D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; }; B538BA771D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; };
B538BA781D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; }; B538BA781D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; };
B538BA791D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; }; B538BA791D15B3E30003A766 /* CoreStoreBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = B538BA701D15B3E30003A766 /* CoreStoreBridge.m */; };
@@ -604,6 +608,7 @@
B529C2031CA4A2DB007E7EBD /* CSSaveResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSSaveResult.swift; sourceTree = "<group>"; }; B529C2031CA4A2DB007E7EBD /* CSSaveResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSSaveResult.swift; sourceTree = "<group>"; };
B52DD1741BE1F8CC00949AFE /* CoreStore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CoreStore.framework; sourceTree = BUILT_PRODUCTS_DIR; }; B52DD1741BE1F8CC00949AFE /* CoreStore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CoreStore.framework; sourceTree = BUILT_PRODUCTS_DIR; };
B52DD17D1BE1F8CC00949AFE /* CoreStoreTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CoreStoreTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; B52DD17D1BE1F8CC00949AFE /* CoreStoreTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CoreStoreTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DispatchQueue+CoreStore.swift"; sourceTree = "<group>"; };
B538BA701D15B3E30003A766 /* CoreStoreBridge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CoreStoreBridge.m; sourceTree = "<group>"; }; B538BA701D15B3E30003A766 /* CoreStoreBridge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CoreStoreBridge.m; sourceTree = "<group>"; };
B53FB9FD1CAB2D2F00F0D40A /* CSMigrationResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSMigrationResult.swift; sourceTree = "<group>"; }; B53FB9FD1CAB2D2F00F0D40A /* CSMigrationResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSMigrationResult.swift; sourceTree = "<group>"; };
B53FBA031CAB300C00F0D40A /* CSMigrationType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSMigrationType.swift; sourceTree = "<group>"; }; B53FBA031CAB300C00F0D40A /* CSMigrationType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CSMigrationType.swift; sourceTree = "<group>"; };
@@ -1199,6 +1204,7 @@
B5E834BA1B7691F3001D3D50 /* Functions.swift */, B5E834BA1B7691F3001D3D50 /* Functions.swift */,
B5FAD6AB1B51285300714891 /* MigrationManager.swift */, B5FAD6AB1B51285300714891 /* MigrationManager.swift */,
B5E84F2B1AFF849C0064E85B /* NotificationObserver.swift */, B5E84F2B1AFF849C0064E85B /* NotificationObserver.swift */,
B533C4DA1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift */,
B5E84F2C1AFF849C0064E85B /* NSManagedObjectContext+CoreStore.swift */, B5E84F2C1AFF849C0064E85B /* NSManagedObjectContext+CoreStore.swift */,
B5E84F351AFF85470064E85B /* NSManagedObjectContext+Querying.swift */, B5E84F351AFF85470064E85B /* NSManagedObjectContext+Querying.swift */,
B5E84F321AFF85470064E85B /* NSManagedObjectContext+Setup.swift */, B5E84F321AFF85470064E85B /* NSManagedObjectContext+Setup.swift */,
@@ -1614,6 +1620,7 @@
B5E2222A1CA51B6E00BA2E95 /* CSUnsafeDataTransaction.swift in Sources */, B5E2222A1CA51B6E00BA2E95 /* CSUnsafeDataTransaction.swift in Sources */,
B5E84F391AFF85470064E85B /* NSManagedObjectContext+Querying.swift in Sources */, B5E84F391AFF85470064E85B /* NSManagedObjectContext+Querying.swift in Sources */,
B5E84EE81AFF84610064E85B /* CoreStoreLogger.swift in Sources */, B5E84EE81AFF84610064E85B /* CoreStoreLogger.swift in Sources */,
B533C4DB1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */,
B559CD491CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */, B559CD491CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */,
B5ECDC2F1CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */, B5ECDC2F1CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */,
B5E84F311AFF849C0064E85B /* WeakObject.swift in Sources */, B5E84F311AFF849C0064E85B /* WeakObject.swift in Sources */,
@@ -1762,6 +1769,7 @@
82BA18A71C4BBD2900A0916E /* CoreStore+Logging.swift in Sources */, 82BA18A71C4BBD2900A0916E /* CoreStore+Logging.swift in Sources */,
82BA18D81C4BBD7100A0916E /* WeakObject.swift in Sources */, 82BA18D81C4BBD7100A0916E /* WeakObject.swift in Sources */,
B559CD4B1CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */, B559CD4B1CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */,
B533C4DC1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */,
B5ECDC311CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */, B5ECDC311CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */,
82BA18AF1C4BBD3100A0916E /* CoreStore+Transaction.swift in Sources */, 82BA18AF1C4BBD3100A0916E /* CoreStore+Transaction.swift in Sources */,
82BA18CB1C4BBD6400A0916E /* NSManagedObject+Convenience.swift in Sources */, 82BA18CB1C4BBD6400A0916E /* NSManagedObject+Convenience.swift in Sources */,
@@ -1910,6 +1918,7 @@
B52DD1A71BE1F93200949AFE /* BaseDataTransaction+Querying.swift in Sources */, B52DD1A71BE1F93200949AFE /* BaseDataTransaction+Querying.swift in Sources */,
B546F96C1C9AF26D00D5AC55 /* CSInMemoryStore.swift in Sources */, B546F96C1C9AF26D00D5AC55 /* CSInMemoryStore.swift in Sources */,
B52DD1C61BE1F94600949AFE /* NSManagedObjectContext+CoreStore.swift in Sources */, B52DD1C61BE1F94600949AFE /* NSManagedObjectContext+CoreStore.swift in Sources */,
B533C4DE1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */,
B5220E141D130614009BC71E /* DataStack+Observing.swift in Sources */, B5220E141D130614009BC71E /* DataStack+Observing.swift in Sources */,
B52DD1A21BE1F92C00949AFE /* CoreStore+Transaction.swift in Sources */, B52DD1A21BE1F92C00949AFE /* CoreStore+Transaction.swift in Sources */,
B5E2222E1CA51B6E00BA2E95 /* CSUnsafeDataTransaction.swift in Sources */, B5E2222E1CA51B6E00BA2E95 /* CSUnsafeDataTransaction.swift in Sources */,
@@ -2058,6 +2067,7 @@
B563219F1BD65216006C9394 /* ObjectMonitor.swift in Sources */, B563219F1BD65216006C9394 /* ObjectMonitor.swift in Sources */,
B56321B61BD6521C006C9394 /* WeakObject.swift in Sources */, B56321B61BD6521C006C9394 /* WeakObject.swift in Sources */,
B559CD4C1CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */, B559CD4C1CAA8C6D00E4D58B /* CSStorageInterface.swift in Sources */,
B533C4DD1D7D4BFA001383CB /* DispatchQueue+CoreStore.swift in Sources */,
B5ECDC321CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */, B5ECDC321CA81CDC00C7F112 /* CSCoreStore+Transaction.swift in Sources */,
B56321AC1BD6521C006C9394 /* Functions.swift in Sources */, B56321AC1BD6521C006C9394 /* Functions.swift in Sources */,
B56321851BD65216006C9394 /* CoreStore+Logging.swift in Sources */, B56321851BD65216006C9394 /* CoreStore+Logging.swift in Sources */,
@@ -2289,10 +2299,7 @@
DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1; DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath"; DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = "$(inherited)";
"$(inherited)",
"$(PROJECT_DIR)/Carthage/Checkouts/GCDKit/build/Debug-appletvos",
);
GCC_NO_COMMON_BLOCKS = YES; GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
@@ -2311,10 +2318,7 @@
DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1; DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath"; DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = "$(inherited)";
"$(inherited)",
"$(PROJECT_DIR)/Carthage/Checkouts/GCDKit/build/Debug-appletvos",
);
GCC_NO_COMMON_BLOCKS = YES; GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+2 -3
View File
@@ -24,7 +24,6 @@
// //
import XCTest import XCTest
import GCDKit
@testable @testable
import CoreStore import CoreStore
@@ -97,7 +96,7 @@ final class FetchTests: BaseTestDataTestCase {
XCTAssertEqual(existing1!.objectID, object.objectID) XCTAssertEqual(existing1!.objectID, object.objectID)
XCTAssertEqual(existing1!.managedObjectContext, transaction.context) XCTAssertEqual(existing1!.managedObjectContext, transaction.context)
GCDQueue.main.async { DispatchQueue.main.async {
let existing2 = stack.fetchExisting(existing1!) let existing2 = stack.fetchExisting(existing1!)
XCTAssertNotNil(existing2) XCTAssertNotNil(existing2)
@@ -204,7 +203,7 @@ final class FetchTests: BaseTestDataTestCase {
XCTAssertEqual(object.managedObjectContext, transaction.context) XCTAssertEqual(object.managedObjectContext, transaction.context)
} }
GCDQueue.main.async { DispatchQueue.main.async {
let existing2 = stack.fetchExisting(existing1) let existing2 = stack.fetchExisting(existing1)
XCTAssertEqual( XCTAssertEqual(
+1 -2
View File
@@ -24,7 +24,6 @@
// //
import XCTest import XCTest
import GCDKit
@testable @testable
import CoreStore import CoreStore
@@ -651,7 +650,7 @@ final class TransactionTests: BaseTestCase {
transaction.delete(object) transaction.delete(object)
GCDQueue.main.async { DispatchQueue.main.async {
XCTAssertEqual(stack.fetchCount(From<TestEntity1>()), 1) XCTAssertEqual(stack.fetchCount(From<TestEntity1>()), 1)
@@ -24,9 +24,6 @@
// //
import Foundation import Foundation
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSProgress // MARK: - NSProgress
@@ -39,7 +36,7 @@ public extension Progress {
- parameter closure: the closure to execute on progress change - parameter closure: the closure to execute on progress change
*/ */
@nonobjc @nonobjc
public func setProgressHandler(_ closure: ((progress: Progress) -> Void)?) { public func setProgressHandler(_ closure: ((_ progress: Progress) -> Void)?) {
self.progressObserver.progressHandler = closure self.progressObserver.progressHandler = closure
} }
@@ -82,7 +79,7 @@ public extension Progress {
private final class ProgressObserver: NSObject { private final class ProgressObserver: NSObject {
private unowned let progress: Progress private unowned let progress: Progress
private var progressHandler: ((progress: Progress) -> Void)? { private var progressHandler: ((_ progress: Progress) -> Void)? {
didSet { didSet {
@@ -132,7 +129,7 @@ private final class ProgressObserver: NSObject {
return return
} }
GCDQueue.main.async { [weak self] () -> Void in DispatchQueue.main.async { [weak self] () -> Void in
self?.progressHandler?(progress: progress) self?.progressHandler?(progress: progress)
} }
+5 -8
View File
@@ -24,9 +24,6 @@
// //
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - CoreStore // MARK: - CoreStore
@@ -45,10 +42,10 @@ public enum CoreStore {
get { get {
self.defaultStackBarrierQueue.barrierSync { self.defaultStackBarrierQueue.sync(flags: .barrier) {
if self.defaultStackInstance == nil { if self.defaultStackInstance == nil {
self.defaultStackInstance = DataStack() self.defaultStackInstance = DataStack()
} }
} }
@@ -56,7 +53,7 @@ public enum CoreStore {
} }
set { set {
self.defaultStackBarrierQueue.barrierAsync { self.defaultStackBarrierQueue.async(flags: .barrier) {
self.defaultStackInstance = newValue self.defaultStackInstance = newValue
} }
@@ -66,7 +63,7 @@ public enum CoreStore {
// MARK: Private // MARK: Private
private static let defaultStackBarrierQueue = GCDQueue.createConcurrent("com.coreStore.defaultStackBarrierQueue") private static let defaultStackBarrierQueue = DispatchQueue(concurrentWith: "com.coreStore.defaultStackBarrierQueue")
private static var defaultStackInstance: DataStack? private static var defaultStackInstance: DataStack?
} }
+2 -2
View File
@@ -32,7 +32,7 @@ import CoreData
/** /**
All errors thrown from CoreStore are expressed in `CoreStoreError` enum values. All errors thrown from CoreStore are expressed in `CoreStoreError` enum values.
*/ */
public enum CoreStoreError: ErrorProtocol, Hashable { public enum CoreStoreError: Error, Hashable {
/** /**
A failure occured because of an unknown error. A failure occured because of an unknown error.
@@ -116,7 +116,7 @@ public enum CoreStoreError: ErrorProtocol, Hashable {
// MARK: Internal // MARK: Internal
internal init(_ error: ErrorProtocol?) { internal init(_ error: Error?) {
self = error.flatMap { $0.bridgeToSwift } ?? .unknown self = error.flatMap { $0.bridgeToSwift } ?? .unknown
} }
@@ -73,7 +73,7 @@ public extension BaseDataTransaction {
- parameter objects: an array of `NSManagedObject`s created/fetched outside the transaction - parameter objects: an array of `NSManagedObject`s created/fetched outside the transaction
- returns: the `NSManagedObject` array for objects that exists in the transaction - returns: the `NSManagedObject` array for objects that exists in the transaction
*/ */
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: Sequence>(_ objects: S) -> [T] where S.Iterator.Element == T {
return objects.flatMap { (try? self.context.existingObject(with: $0.objectID)) as? T } return objects.flatMap { (try? self.context.existingObject(with: $0.objectID)) as? T }
} }
@@ -84,7 +84,7 @@ public extension BaseDataTransaction {
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the transaction - returns: the `NSManagedObject` array for objects that exists in the transaction
*/ */
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: Sequence>(_ objectIDs: S) -> [T] where S.Iterator.Element == NSManagedObjectID {
return objectIDs.flatMap { (try? self.context.existingObject(with: $0)) as? T } return objectIDs.flatMap { (try? self.context.existingObject(with: $0)) as? T }
} }
@@ -201,7 +201,7 @@ public struct From<T: NSManagedObject> {
internal func applyAffectedStoresForFetchedRequest<U: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<U>, context: NSManagedObjectContext) -> Bool { internal func applyAffectedStoresForFetchedRequest<U: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<U>, context: NSManagedObjectContext) -> Bool {
let stores = self.findPersistentStores(context: context) let stores = self.findPersistentStores(context)
fetchRequest.affectedStores = stores fetchRequest.affectedStores = stores
return stores?.isEmpty == false return stores?.isEmpty == false
} }
@@ -218,7 +218,7 @@ public struct From<T: NSManagedObject> {
// MARK: Private // MARK: Private
private let findPersistentStores: (context: NSManagedObjectContext) -> [NSPersistentStore]? private let findPersistentStores: (_ context: NSManagedObjectContext) -> [NSPersistentStore]?
private init(entityClass: AnyClass, configurations: [String?]?) { private init(entityClass: AnyClass, configurations: [String?]?) {
@@ -244,7 +244,7 @@ public struct From<T: NSManagedObject> {
} }
} }
private init(entityClass: AnyClass, configurations: [String?]?, findPersistentStores: (context: NSManagedObjectContext) -> [NSPersistentStore]?) { private init(entityClass: AnyClass, configurations: [String?]?, findPersistentStores: @escaping (_ context: NSManagedObjectContext) -> [NSPersistentStore]?) {
self.entityClass = entityClass self.entityClass = entityClass
self.configurations = configurations self.configurations = configurations
@@ -72,14 +72,14 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
/** /**
The list of sort descriptors The list of sort descriptors
*/ */
public let sortDescriptors: [SortDescriptor] public let sortDescriptors: [NSSortDescriptor]
/** /**
Initializes a `OrderBy` clause with an empty list of sort descriptors Initializes a `OrderBy` clause with an empty list of sort descriptors
*/ */
public init() { public init() {
self.init([SortDescriptor]()) self.init([NSSortDescriptor]())
} }
/** /**
@@ -87,7 +87,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter sortDescriptor: a `NSSortDescriptor` - parameter sortDescriptor: a `NSSortDescriptor`
*/ */
public init(_ sortDescriptor: SortDescriptor) { public init(_ sortDescriptor: NSSortDescriptor) {
self.init([sortDescriptor]) self.init([sortDescriptor])
} }
@@ -97,7 +97,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter sortDescriptors: a series of `NSSortDescriptor`s - parameter sortDescriptors: a series of `NSSortDescriptor`s
*/ */
public init(_ sortDescriptors: [SortDescriptor]) { public init(_ sortDescriptors: [NSSortDescriptor]) {
self.sortDescriptors = sortDescriptors self.sortDescriptors = sortDescriptors
} }
@@ -110,7 +110,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
public init(_ sortKey: [SortKey]) { public init(_ sortKey: [SortKey]) {
self.init( self.init(
sortKey.map { sortKey -> SortDescriptor in sortKey.map { sortKey -> NSSortDescriptor in
switch sortKey { switch sortKey {
@@ -64,7 +64,7 @@ public protocol SelectAttributesResultType: SelectResultType {
/** /**
The `SelectTerm` is passed to the `Select` clause to indicate the attributes/aggregate keys to be queried. The `SelectTerm` is passed to the `Select` clause to indicate the attributes/aggregate keys to be queried.
*/ */
public enum SelectTerm: StringLiteralConvertible, Hashable { public enum SelectTerm: ExpressibleByStringLiteral, Hashable {
/** /**
Provides a `SelectTerm` to a `Select` clause for querying an entity attribute. A shorter way to do the same is to assign from the string keypath directly: Provides a `SelectTerm` to a `Select` clause for querying an entity attribute. A shorter way to do the same is to assign from the string keypath directly:
@@ -223,7 +223,7 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
} }
// MARK: StringLiteralConvertible // MARK: ExpressibleByStringLiteral
public init(stringLiteral value: KeyPath) { public init(stringLiteral value: KeyPath) {
@@ -367,7 +367,7 @@ public struct Select<T: SelectResultType>: Hashable {
public var hashValue: Int { public var hashValue: Int {
return self.selectTerms.map { $0.hashValue }.reduce(0, combine: ^) return self.selectTerms.map { $0.hashValue }.reduce(0, ^)
} }
@@ -47,7 +47,7 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
/** /**
The block to customize the `NSFetchRequest` The block to customize the `NSFetchRequest`
*/ */
public let closure: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void public let closure: (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void
/** /**
Initializes a `Tweak` clause with a closure where the `NSFetchRequest` may be configured. Initializes a `Tweak` clause with a closure where the `NSFetchRequest` may be configured.
@@ -55,7 +55,7 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
- Important: `Tweak`'s closure is executed only just before the fetch occurs, so make sure that any values captured by the closure is not prone to race conditions. Also, some utilities (such as `ListMonitor`s) may keep `FetchClause`s in memory and may thus introduce retain cycles if reference captures are not handled properly. - Important: `Tweak`'s closure is executed only just before the fetch occurs, so make sure that any values captured by the closure is not prone to race conditions. Also, some utilities (such as `ListMonitor`s) may keep `FetchClause`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter closure: the block to customize the `NSFetchRequest` - parameter closure: the block to customize the `NSFetchRequest`
*/ */
public init(_ closure: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) { public init(_ closure: @escaping (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) {
self.closure = closure self.closure = closure
} }
@@ -65,6 +65,6 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) { public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
self.closure(fetchRequest: unsafeBitCast(fetchRequest, to: NSFetchRequest<NSFetchRequestResult>.self)) self.closure(unsafeBitCast(fetchRequest, to: NSFetchRequest<NSFetchRequestResult>.self))
} }
} }
@@ -29,17 +29,17 @@ import CoreData
public func && (left: Where, right: Where) -> Where { public func && (left: Where, right: Where) -> Where {
return Where(CompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])) return Where(NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate]))
} }
public func || (left: Where, right: Where) -> Where { public func || (left: Where, right: Where) -> Where {
return Where(CompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate])) return Where(NSCompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate]))
} }
public prefix func ! (clause: Where) -> Where { public prefix func ! (clause: Where) -> Where {
return Where(CompoundPredicate(type: .not, subpredicates: [clause.predicate])) return Where(NSCompoundPredicate(type: .not, subpredicates: [clause.predicate]))
} }
@@ -53,7 +53,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
/** /**
The `NSPredicate` for the fetch or query The `NSPredicate` for the fetch or query
*/ */
public let predicate: Predicate public let predicate: NSPredicate
/** /**
Initializes a `Where` clause with a predicate that always evaluates to `true` Initializes a `Where` clause with a predicate that always evaluates to `true`
@@ -70,7 +70,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/ */
public init(_ value: Bool) { public init(_ value: Bool) {
self.init(Predicate(value: value)) self.init(NSPredicate(value: value))
} }
/** /**
@@ -81,7 +81,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/ */
public init(_ format: String, _ args: NSObject...) { public init(_ format: String, _ args: NSObject...) {
self.init(Predicate(format: format, argumentArray: args)) self.init(NSPredicate(format: format, argumentArray: args))
} }
/** /**
@@ -92,7 +92,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/ */
public init(_ format: String, argumentArray: [NSObject]?) { public init(_ format: String, argumentArray: [NSObject]?) {
self.init(Predicate(format: format, argumentArray: argumentArray)) self.init(NSPredicate(format: format, argumentArray: argumentArray))
} }
/** /**
@@ -104,8 +104,8 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
public init(_ keyPath: KeyPath, isEqualTo value: NSObject?) { public init(_ keyPath: KeyPath, isEqualTo value: NSObject?) {
self.init(value == nil self.init(value == nil
? Predicate(format: "\(keyPath) == nil") ? NSPredicate(format: "\(keyPath) == nil")
: Predicate(format: "\(keyPath) == %@", argumentArray: [value!])) : NSPredicate(format: "\(keyPath) == %@", argumentArray: [value!]))
} }
/** /**
@@ -116,7 +116,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/ */
public init(_ keyPath: KeyPath, isMemberOf list: [NSObject]) { public init(_ keyPath: KeyPath, isMemberOf list: [NSObject]) {
self.init(Predicate(format: "\(keyPath) IN %@", list)) self.init(NSPredicate(format: "\(keyPath) IN %@", list))
} }
/** /**
@@ -125,9 +125,9 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter keyPath: the keyPath to compare with - parameter keyPath: the keyPath to compare with
- parameter list: the sequence to check membership of - parameter list: the sequence to check membership of
*/ */
public init<S: Sequence where S.Iterator.Element: NSObject>(_ keyPath: KeyPath, isMemberOf list: S) { public init<S: Sequence>(_ keyPath: KeyPath, isMemberOf list: S) where S.Iterator.Element: NSObject {
self.init(Predicate(format: "\(keyPath) IN %@", Array(list) as NSArray)) self.init(NSPredicate(format: "\(keyPath) IN %@", Array(list) as NSArray))
} }
/** /**
@@ -135,7 +135,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter predicate: the `NSPredicate` for the fetch or query - parameter predicate: the `NSPredicate` for the fetch or query
*/ */
public init(_ predicate: Predicate) { public init(_ predicate: NSPredicate) {
self.predicate = predicate self.predicate = predicate
} }
@@ -59,7 +59,7 @@ public extension CoreStore {
- parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack` - parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack`
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
public static func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] { public static func fetchExisting<T: NSManagedObject, S: Sequence>(_ objects: S) -> [T] where S.Iterator.Element == T {
return self.defaultStack.fetchExisting(objects) return self.defaultStack.fetchExisting(objects)
} }
@@ -70,7 +70,7 @@ public extension CoreStore {
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
public static func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] { public static func fetchExisting<T: NSManagedObject, S: Sequence>(_ objectIDs: S) -> [T] where S.Iterator.Element == NSManagedObjectID {
return self.defaultStack.fetchExisting(objectIDs) return self.defaultStack.fetchExisting(objectIDs)
} }
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - DataStack // MARK: - DataStack
@@ -76,7 +73,7 @@ public extension DataStack {
- parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack` - parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack`
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: Sequence>(_ objects: S) -> [T] where S.Iterator.Element == T {
return objects.flatMap { (try? self.mainContext.existingObject(with: $0.objectID)) as? T } return objects.flatMap { (try? self.mainContext.existingObject(with: $0.objectID)) as? T }
} }
@@ -87,7 +84,7 @@ public extension DataStack {
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: Sequence>(_ objectIDs: S) -> [T] where S.Iterator.Element == NSManagedObjectID {
return objectIDs.flatMap { (try? self.mainContext.existingObject(with: $0)) as? T } return objectIDs.flatMap { (try? self.mainContext.existingObject(with: $0)) as? T }
} }
@@ -39,9 +39,9 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableObject` methods - throws: an `ErrorType` thrown from any of the `ImportableObject` methods
- returns: the created `ImportableObject` instance, or `nil` if the import was ignored - returns: the created `ImportableObject` instance, or `nil` if the import was ignored
*/ */
public func importObject<T where T: NSManagedObject, T: ImportableObject>( public func importObject<T>(
_ into: Into<T>, _ into: Into<T>,
source: T.ImportSource) throws -> T? { source: T.ImportSource) throws -> T? where T: NSManagedObject, T: ImportableObject {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -68,9 +68,9 @@ public extension BaseDataTransaction {
- parameter source: the object to import values from - parameter source: the object to import values from
- throws: an `ErrorType` thrown from any of the `ImportableObject` methods - throws: an `ErrorType` thrown from any of the `ImportableObject` methods
*/ */
public func importObject<T where T: NSManagedObject, T: ImportableObject>( public func importObject<T>(
_ object: T, _ object: T,
source: T.ImportSource) throws { source: T.ImportSource) throws where T: NSManagedObject, T: ImportableObject {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -96,9 +96,9 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableObject` methods - throws: an `ErrorType` thrown from any of the `ImportableObject` methods
- returns: the array of created `ImportableObject` instances - returns: the array of created `ImportableObject` instances
*/ */
public func importObjects<T, S: Sequence where T: NSManagedObject, T: ImportableObject, S.Iterator.Element == T.ImportSource>( public func importObjects<T, S: Sequence>(
_ into: Into<T>, _ into: Into<T>,
sourceArray: S) throws -> [T] { sourceArray: S) throws -> [T] where T: NSManagedObject, T: ImportableObject, S.Iterator.Element == T.ImportSource {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -132,9 +132,9 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableUniqueObject` methods - throws: an `ErrorType` thrown from any of the `ImportableUniqueObject` methods
- returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored - returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored
*/ */
public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>( public func importUniqueObject<T>(
_ into: Into<T>, _ into: Into<T>,
source: T.ImportSource) throws -> T? { source: T.ImportSource) throws -> T? where T: NSManagedObject, T: ImportableUniqueObject {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -184,10 +184,10 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableUniqueObject` methods - throws: an `ErrorType` thrown from any of the `ImportableUniqueObject` methods
- returns: the array of created/updated `ImportableUniqueObject` instances - returns: the array of created/updated `ImportableUniqueObject` instances
*/ */
public func importUniqueObjects<T, S: Sequence where T: NSManagedObject, T: ImportableUniqueObject, S.Iterator.Element == T.ImportSource>( public func importUniqueObjects<T, S: Sequence>(
_ into: Into<T>, _ into: Into<T>,
sourceArray: S, sourceArray: S,
preProcess: @noescape (mapping: [T.UniqueIDType: T.ImportSource]) throws -> [T.UniqueIDType: T.ImportSource] = { $0 }) throws -> [T] { preProcess: @escaping (_ mapping: [T.UniqueIDType: T.ImportSource]) throws -> [T.UniqueIDType: T.ImportSource] = { $0 }) throws -> [T] where T: NSManagedObject, T: ImportableUniqueObject, S.Iterator.Element == T.ImportSource {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -211,7 +211,7 @@ public extension BaseDataTransaction {
} }
} }
mapping = try autoreleasepool { try preProcess(mapping: mapping) } mapping = try autoreleasepool { try preProcess(mapping) }
var objects = Dictionary<T.UniqueIDType, T>() var objects = Dictionary<T.UniqueIDType, T>()
for object in self.fetchAll(From<T>(), Where(T.uniqueIDKeyPath, isMemberOf: sortedIDs)) ?? [] { for object in self.fetchAll(From<T>(), Where(T.uniqueIDKeyPath, isMemberOf: sortedIDs)) ?? [] {
@@ -36,7 +36,7 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
// MARK: Internal // MARK: Internal
@nonobjc @nonobjc
internal convenience init<T: NSManagedObject>(dataStack: DataStack, fetchRequest: NSFetchRequest<NSManagedObject>, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) { internal convenience init<T: NSManagedObject>(dataStack: DataStack, fetchRequest: NSFetchRequest<NSManagedObject>, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
self.init( self.init(
context: dataStack.mainContext, context: dataStack.mainContext,
@@ -48,14 +48,14 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
} }
@nonobjc @nonobjc
internal init<T: NSManagedObject>(context: NSManagedObjectContext, fetchRequest: NSFetchRequest<NSManagedObject>, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) { internal init<T: NSManagedObject>(context: NSManagedObjectContext, fetchRequest: NSFetchRequest<NSManagedObject>, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
_ = from?.applyToFetchRequest( _ = from?.applyToFetchRequest(
fetchRequest, fetchRequest,
context: context, context: context,
applyAffectedStores: false applyAffectedStores: false
) )
applyFetchClauses(fetchRequest: unsafeBitCast(fetchRequest, to: NSFetchRequest<NSManagedObject>.self)) applyFetchClauses(unsafeBitCast(fetchRequest, to: NSFetchRequest<NSManagedObject>.self))
if let from = from { if let from = from {
@@ -88,7 +88,7 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
@nonobjc @nonobjc
internal func performFetchFromSpecifiedStores() throws { internal func performFetchFromSpecifiedStores() throws {
if !self.reapplyAffectedStores(fetchRequest: self.fetchRequest, context: self.managedObjectContext) { if !self.reapplyAffectedStores(self.fetchRequest, self.managedObjectContext) {
CoreStore.log( CoreStore.log(
.warning, .warning,
@@ -113,7 +113,7 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
// MARK: Private // MARK: Private
@nonobjc @nonobjc
private let reapplyAffectedStores: (fetchRequest: NSFetchRequest<NSManagedObject>, context: NSManagedObjectContext) -> Bool private let reapplyAffectedStores: (_ fetchRequest: NSFetchRequest<NSManagedObject>, _ context: NSManagedObjectContext) -> Bool
} }
#endif #endif
@@ -0,0 +1,90 @@
//
// DispatchQueue+CoreStore.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: - DispatchQueue
internal extension DispatchQueue {
internal convenience init(serialWith label: String) {
self.init(
label: label,
qos: .default,
attributes: .allZeros,
autoreleaseFrequency: .inherit,
target: nil
)
}
internal convenience init(concurrentWith label: String) {
self.init(
label: label,
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil
)
}
internal func cs_isCurrentExecutionContext() -> Bool {
let specific = ObjectIdentifier(self)
self.setSpecific(key: Static.specificKey, value: specific)
return DispatchQueue.getSpecific(key: Static.specificKey) == specific
}
internal func cs_sync<T>(_ closure: () throws -> T) rethrows -> T {
return self.sync { autoreleasepool(invoking: closure) }
}
internal func cs_async(_ closure: () -> Void) {
self.async { autoreleasepool(invoking: closure) }
}
internal func cs_barrierSync<T>(_ closure: () throws -> T) rethrows -> T {
return self.sync(flags: .barrier) { autoreleasepool(invoking: closure) }
}
internal func cs_barrierAsync(_ closure: () -> Void) {
self.async(flags: .barrier) { autoreleasepool(invoking: closure) }
}
// MARK: Private
private enum Static {
static let specificKey = DispatchSpecificKey<ObjectIdentifier>()
}
}
+5 -5
View File
@@ -27,7 +27,7 @@ import Foundation
// MARK: Associated Objects // MARK: Associated Objects
internal func cs_getAssociatedObjectForKey<T: AnyObject>(_ key: UnsafePointer<Void>, inObject object: AnyObject) -> T? { internal func cs_getAssociatedObjectForKey<T: AnyObject>(_ key: UnsafeRawPointer, inObject object: AnyObject) -> T? {
switch objc_getAssociatedObject(object, key) { switch objc_getAssociatedObject(object, key) {
@@ -42,17 +42,17 @@ internal func cs_getAssociatedObjectForKey<T: AnyObject>(_ key: UnsafePointer<Vo
} }
} }
internal func cs_setAssociatedRetainedObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafePointer<Void>, inObject object: AnyObject) { internal func cs_setAssociatedRetainedObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafeRawPointer, inObject object: AnyObject) {
objc_setAssociatedObject(object, key, associatedObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(object, key, associatedObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} }
internal func cs_setAssociatedCopiedObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafePointer<Void>, inObject object: AnyObject) { internal func cs_setAssociatedCopiedObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafeRawPointer, inObject object: AnyObject) {
objc_setAssociatedObject(object, key, associatedObject, .OBJC_ASSOCIATION_COPY_NONATOMIC) objc_setAssociatedObject(object, key, associatedObject, .OBJC_ASSOCIATION_COPY_NONATOMIC)
} }
internal func cs_setAssociatedWeakObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafePointer<Void>, inObject object: AnyObject) { internal func cs_setAssociatedWeakObject<T: AnyObject>(_ associatedObject: T?, forKey key: UnsafeRawPointer, inObject object: AnyObject) {
if let associatedObject = associatedObject { if let associatedObject = associatedObject {
@@ -69,7 +69,7 @@ internal func cs_setAssociatedWeakObject<T: AnyObject>(_ associatedObject: T?, f
internal func cs_typeName<T>(_ value: T) -> String { internal func cs_typeName<T>(_ value: T) -> String {
return "'\(String(reflecting: value.dynamicType))'" return "'\(String(reflecting: type(of: value)))'"
} }
internal func cs_typeName<T>(_ value: T.Type) -> String { internal func cs_typeName<T>(_ value: T.Type) -> String {
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSManagedObjectContext // MARK: - NSManagedObjectContext
@@ -99,7 +99,7 @@ internal extension NSManagedObjectContext {
internal func fetchOne<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> T? { internal func fetchOne<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> T? {
var fetchResults: [T]? var fetchResults: [T]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -152,7 +152,7 @@ internal extension NSManagedObjectContext {
internal func fetchAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> [T]? { internal func fetchAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> [T]? {
var fetchResults: [T]? var fetchResults: [T]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -202,7 +202,7 @@ internal extension NSManagedObjectContext {
internal func fetchCount(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Int? { internal func fetchCount(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Int? {
var count = 0 var count = 0
var countError: ErrorProtocol? var countError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -255,7 +255,7 @@ internal extension NSManagedObjectContext {
internal func fetchObjectID(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> NSManagedObjectID? { internal func fetchObjectID(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> NSManagedObjectID? {
var fetchResults: [NSManagedObjectID]? var fetchResults: [NSManagedObjectID]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -308,7 +308,7 @@ internal extension NSManagedObjectContext {
internal func fetchObjectIDs(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> [NSManagedObjectID]? { internal func fetchObjectIDs(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> [NSManagedObjectID]? {
var fetchResults: [NSManagedObjectID]? var fetchResults: [NSManagedObjectID]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -363,7 +363,7 @@ internal extension NSManagedObjectContext {
internal func deleteAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> Int? { internal func deleteAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> Int? {
var numberOfDeletedObjects: Int? var numberOfDeletedObjects: Int?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
autoreleasepool { autoreleasepool {
@@ -426,7 +426,7 @@ internal extension NSManagedObjectContext {
internal func queryValue<U: SelectValueResultType>(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> U? { internal func queryValue<U: SelectValueResultType>(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> U? {
var fetchResults: [AnyObject]? var fetchResults: [AnyObject]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -459,7 +459,7 @@ internal extension NSManagedObjectContext {
internal func queryValue(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> AnyObject? { internal func queryValue(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> AnyObject? {
var fetchResults: [AnyObject]? var fetchResults: [AnyObject]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -519,7 +519,7 @@ internal extension NSManagedObjectContext {
internal func queryAttributes(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> [[NSString: AnyObject]]? { internal func queryAttributes(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> [[NSString: AnyObject]]? {
var fetchResults: [AnyObject]? var fetchResults: [AnyObject]?
var fetchError: ErrorProtocol? var fetchError: Error?
self.performAndWait { self.performAndWait {
do { do {
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSManagedObjectContext // MARK: - NSManagedObjectContext
@@ -150,13 +147,13 @@ internal extension NSManagedObjectContext {
} }
@nonobjc @nonobjc
internal func saveAsynchronouslyWithCompletion(_ completion: ((result: SaveResult) -> Void) = { _ in }) { internal func saveAsynchronouslyWithCompletion(_ completion: ((_ result: SaveResult) -> Void) = { _ in }) {
self.perform { self.perform {
guard self.hasChanges else { guard self.hasChanges else {
GCDQueue.main.async { DispatchQueue.main.async {
completion(result: SaveResult(hasChanges: false)) completion(result: SaveResult(hasChanges: false))
} }
@@ -176,7 +173,7 @@ internal extension NSManagedObjectContext {
saveError, saveError,
"Failed to save \(cs_typeName(NSManagedObjectContext.self))." "Failed to save \(cs_typeName(NSManagedObjectContext.self))."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(result: SaveResult(saveError)) completion(result: SaveResult(saveError))
} }
@@ -189,7 +186,7 @@ internal extension NSManagedObjectContext {
} }
else { else {
GCDQueue.main.async { DispatchQueue.main.async {
completion(result: SaveResult(hasChanges: true)) completion(result: SaveResult(hasChanges: true))
} }
@@ -36,7 +36,7 @@ internal extension NSManagedObjectModel {
@nonobjc @nonobjc
internal static func fromBundle(_ bundle: Bundle, modelName: String, modelVersionHints: Set<String> = []) -> NSManagedObjectModel { internal static func fromBundle(_ bundle: Bundle, modelName: String, modelVersionHints: Set<String> = []) -> NSManagedObjectModel {
guard let modelFilePath = bundle.pathForResource(modelName, ofType: "momd") else { guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else {
CoreStore.abort("Could not find \"\(modelName).momd\" from the bundle. \(bundle)") CoreStore.abort("Could not find \"\(modelName).momd\" from the bundle. \(bundle)")
} }
@@ -26,23 +26,19 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSPersistentStoreCoordinator // MARK: - NSPersistentStoreCoordinator
internal extension NSPersistentStoreCoordinator { internal extension NSPersistentStoreCoordinator {
@nonobjc @nonobjc
internal func performAsynchronously(_ closure: () -> Void) { internal func performAsynchronously(_ closure: @escaping () -> Void) {
self.perform(closure) self.perform(closure)
} }
@nonobjc @nonobjc
internal func performSynchronously<T>(_ closure: () -> T) -> T { internal func performSynchronously<T>(_ closure: @escaping () -> T) -> T {
var result: T? var result: T?
self.performAndWait { self.performAndWait {
@@ -53,9 +49,9 @@ internal extension NSPersistentStoreCoordinator {
} }
@nonobjc @nonobjc
internal func performSynchronously<T>(_ closure: () throws -> T) throws -> T { internal func performSynchronously<T>(_ closure: @escaping () throws -> T) throws -> T {
var closureError: ErrorProtocol? var closureError: Error?
var result: T? var result: T?
self.performAndWait { self.performAndWait {
+1 -1
View File
@@ -36,7 +36,7 @@ internal final class NotificationObserver {
let object: AnyObject? let object: AnyObject?
let observer: NSObjectProtocol let observer: NSObjectProtocol
init(notificationName: Notification.Name, object: AnyObject?, queue: OperationQueue? = nil, closure: (note: Notification) -> Void) { init(notificationName: Notification.Name, object: AnyObject?, queue: OperationQueue? = nil, closure: @escaping (_ note: Notification) -> Void) {
self.notificationName = notificationName self.notificationName = notificationName
self.object = object self.object = object
@@ -912,7 +912,7 @@ private func formattedValue(_ any: Any) -> String {
private func formattedDebugDescription(_ any: Any) -> String { private func formattedDebugDescription(_ any: Any) -> String {
var string = "(\(String(reflecting: any.dynamicType))) " var string = "(\(String(reflecting: type(of: any)))) "
string.append(formattedValue(any)) string.append(formattedValue(any))
return string return string
} }
@@ -1163,7 +1163,7 @@ extension NSMappingModel: CoreStoreDebugStringConvertible {
} }
} }
extension Predicate: CoreStoreDebugStringConvertible { extension NSPredicate: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String { public var coreStoreDumpString: String {
@@ -1199,7 +1199,7 @@ extension NSRelationshipDescription: CoreStoreDebugStringConvertible {
} }
} }
extension SortDescriptor: CoreStoreDebugStringConvertible { extension NSSortDescriptor: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String { public var coreStoreDumpString: String {
+2 -2
View File
@@ -71,8 +71,8 @@ public extension CoreStore {
) )
} }
@noreturn
internal static func abort(_ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) { internal static func abort(_ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) -> Never {
self.logger.abort( self.logger.abort(
message, message,
+2 -5
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - CoreStore // MARK: - CoreStore
@@ -50,7 +47,7 @@ public extension CoreStore {
- parameter storeType: the storage type - parameter storeType: the storage type
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration.
*/ */
public static func addStorage<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) { public static func addStorage<T: StorageInterface>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) where T: DefaultInitializableStore {
self.defaultStack.addStorage(storeType.init(), completion: completion) self.defaultStack.addStorage(storeType.init(), completion: completion)
} }
@@ -93,7 +90,7 @@ public extension CoreStore {
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration.
- returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured. - returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured.
*/ */
public static func addStorage<T: LocalStorage where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? { public static func addStorage<T: LocalStorage>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? where T: DefaultInitializableStore {
return self.defaultStack.addStorage(storeType.init(), completion: completion) return self.defaultStack.addStorage(storeType.init(), completion: completion)
} }
+39 -42
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - DataStack // MARK: - DataStack
@@ -50,7 +47,7 @@ public extension DataStack {
- parameter storeType: the storage type - parameter storeType: the storage type
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration.
*/ */
public func addStorage<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) { public func addStorage<T: StorageInterface>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) where T: DefaultInitializableStore {
self.addStorage(storeType.init(), completion: completion) self.addStorage(storeType.init(), completion: completion)
} }
@@ -71,13 +68,13 @@ public extension DataStack {
- parameter storage: the storage - parameter storage: the storage
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration.
*/ */
public func addStorage<T: StorageInterface>(_ storage: T, completion: (SetupResult<T>) -> Void) { public func addStorage<T: StorageInterface>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) {
self.coordinator.performAsynchronously { self.coordinator.performAsynchronously {
if let _ = self.persistentStoreForStorage(storage) { if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -92,7 +89,7 @@ public extension DataStack {
finalStoreOptions: storage.storeOptions finalStoreOptions: storage.storeOptions
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -104,7 +101,7 @@ public extension DataStack {
storeError, storeError,
"Failed to add \(cs_typeName(storage)) to the stack." "Failed to add \(cs_typeName(storage)) to the stack."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storeError)) completion(SetupResult(storeError))
} }
@@ -129,9 +126,9 @@ public extension DataStack {
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration.
- returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured. - returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured.
*/ */
public func addStorage<T: LocalStorage where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? { public func addStorage<T: LocalStorage>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? where T: DefaultInitializableStore {
return self.addStorage(storeType.init(), completion: completion) return self.addStorage(storeType.init() as! T.Type, completion: completion)
} }
/** /**
@@ -151,7 +148,7 @@ public extension DataStack {
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration.
- returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured. - returns: an `NSProgress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured.
*/ */
public func addStorage<T: LocalStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) -> Progress? { public func addStorage<T: LocalStorage>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) -> Progress? {
let fileURL = storage.fileURL let fileURL = storage.fileURL
CoreStore.assert( CoreStore.assert(
@@ -163,7 +160,7 @@ public extension DataStack {
if let _ = self.persistentStoreForStorage(storage) { if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -175,7 +172,7 @@ public extension DataStack {
if let existingStorage = persistentStore.storageInterface as? T, if let existingStorage = persistentStore.storageInterface as? T,
storage.matchesPersistentStore(persistentStore) { storage.matchesPersistentStore(persistentStore) {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(existingStorage)) completion(SetupResult(existingStorage))
} }
@@ -187,7 +184,7 @@ public extension DataStack {
error, error,
"Failed to add \(cs_typeName(storage)) at \"\(fileURL)\" because a different \(cs_typeName(NSPersistentStore.self)) at that URL already exists." "Failed to add \(cs_typeName(storage)) at \"\(fileURL)\" because a different \(cs_typeName(NSPersistentStore.self)) at that URL already exists."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(error)) completion(SetupResult(error))
} }
@@ -203,14 +200,14 @@ public extension DataStack {
) )
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: fileURL as URL, at: fileURL as URL,
options: storage.storeOptions options: storage.storeOptions
) )
return self.upgradeStorageIfNeeded( return self.upgradeStorageIfNeeded(
storage, storage,
metadata: metadata, metadata: metadata as [String : AnyObject],
completion: { (result) -> Void in completion: { (result) -> Void in
if case .failure(.internalError(let error)) = result { if case .failure(.internalError(let error)) = result {
@@ -222,7 +219,7 @@ public extension DataStack {
_ = try self.model[metadata].flatMap(storage.eraseStorageAndWait) _ = try self.model[metadata].flatMap(storage.eraseStorageAndWait)
_ = try self.addStorageAndWait(storage) _ = try self.addStorageAndWait(storage)
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -258,14 +255,14 @@ public extension DataStack {
_ = try self.addStorageAndWait(storage) _ = try self.addStorageAndWait(storage)
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
} }
catch { catch {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(error)) completion(SetupResult(error))
} }
@@ -279,7 +276,7 @@ public extension DataStack {
storeError, storeError,
"Failed to load SQLite \(cs_typeName(NSPersistentStore.self)) metadata." "Failed to load SQLite \(cs_typeName(NSPersistentStore.self)) metadata."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storeError)) completion(SetupResult(storeError))
} }
@@ -315,14 +312,14 @@ public extension DataStack {
- parameter storage: the cloud storage - parameter storage: the cloud storage
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `CloudStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `CloudStorage` was already added at the same URL and with the same configuration. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `CloudStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `CloudStorage` was already added at the same URL and with the same configuration.
*/ */
public func addStorage<T: CloudStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) { public func addStorage<T: CloudStorage>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) {
let cacheFileURL = storage.cacheFileURL let cacheFileURL = storage.cacheFileURL
self.coordinator.performSynchronously { self.coordinator.performSynchronously {
if let _ = self.persistentStoreForStorage(storage) { if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -334,7 +331,7 @@ public extension DataStack {
if let existingStorage = persistentStore.storageInterface as? T, if let existingStorage = persistentStore.storageInterface as? T,
storage.matchesPersistentStore(persistentStore) { storage.matchesPersistentStore(persistentStore) {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(existingStorage)) completion(SetupResult(existingStorage))
} }
@@ -346,7 +343,7 @@ public extension DataStack {
error, error,
"Failed to add \(cs_typeName(storage)) at \"\(cacheFileURL)\" because a different \(cs_typeName(NSPersistentStore.self)) at that URL already exists." "Failed to add \(cs_typeName(storage)) at \"\(cacheFileURL)\" because a different \(cs_typeName(NSPersistentStore.self)) at that URL already exists."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(error)) completion(SetupResult(error))
} }
@@ -371,7 +368,7 @@ public extension DataStack {
finalURL: cacheFileURL, finalURL: cacheFileURL,
finalStoreOptions: storeOptions finalStoreOptions: storeOptions
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
@@ -379,7 +376,7 @@ public extension DataStack {
catch let error as NSError where storage.cloudStorageOptions.contains(.recreateLocalStoreOnModelMismatch) && error.isCoreDataMigrationError { catch let error as NSError where storage.cloudStorageOptions.contains(.recreateLocalStoreOnModelMismatch) && error.isCoreDataMigrationError {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: cacheFileURL, at: cacheFileURL,
options: storeOptions options: storeOptions
) )
@@ -398,14 +395,14 @@ public extension DataStack {
_ = try self.addStorageAndWait(storage) _ = try self.addStorageAndWait(storage)
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storage)) completion(SetupResult(storage))
} }
} }
catch { catch {
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(error)) completion(SetupResult(error))
} }
@@ -418,7 +415,7 @@ public extension DataStack {
storeError, storeError,
"Failed to load \(cs_typeName(NSPersistentStore.self)) metadata." "Failed to load \(cs_typeName(NSPersistentStore.self)) metadata."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(SetupResult(storeError)) completion(SetupResult(storeError))
} }
@@ -447,13 +444,13 @@ public extension DataStack {
) )
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: fileURL as URL, at: fileURL as URL,
options: storage.storeOptions options: storage.storeOptions
) )
return self.upgradeStorageIfNeeded( return self.upgradeStorageIfNeeded(
storage, storage,
metadata: metadata, metadata: metadata as [String : AnyObject],
completion: completion completion: completion
) )
} }
@@ -489,12 +486,12 @@ public extension DataStack {
do { do {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: fileURL as URL, at: fileURL as URL,
options: storage.storeOptions options: storage.storeOptions
) )
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else { guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata as [String : AnyObject]) else {
let error = CoreStoreError.mappingModelNotFound( let error = CoreStoreError.mappingModelNotFound(
localStoreURL: fileURL, localStoreURL: fileURL,
@@ -540,7 +537,7 @@ public extension DataStack {
// MARK: Private // MARK: Private
private func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, metadata: [String: AnyObject], completion: (MigrationResult) -> Void) -> Progress? { private func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, metadata: [String: AnyObject], completion: @escaping (MigrationResult) -> Void) -> Progress? {
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else { guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else {
@@ -554,7 +551,7 @@ public extension DataStack {
"Failed to find migration steps from \(cs_typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.model)\"." "Failed to find migration steps from \(cs_typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.model)\"."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(MigrationResult(error)) completion(MigrationResult(error))
} }
@@ -564,7 +561,7 @@ public extension DataStack {
let numberOfMigrations: Int64 = Int64(migrationSteps.count) let numberOfMigrations: Int64 = Int64(migrationSteps.count)
if numberOfMigrations == 0 { if numberOfMigrations == 0 {
GCDQueue.main.async { DispatchQueue.main.async {
completion(MigrationResult([])) completion(MigrationResult([]))
return return
@@ -578,7 +575,7 @@ public extension DataStack {
error, error,
"Failed to find migration mapping from the \(cs_typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.modelVersion)\" without requiring progessive migrations." "Failed to find migration mapping from the \(cs_typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.modelVersion)\" without requiring progessive migrations."
) )
GCDQueue.main.async { DispatchQueue.main.async {
completion(MigrationResult(error)) completion(MigrationResult(error))
} }
@@ -627,7 +624,7 @@ public extension DataStack {
} }
} }
GCDQueue.main.async { DispatchQueue.main.async {
_ = withExtendedLifetime(childProgress) { (_: Progress) -> Void in } _ = withExtendedLifetime(childProgress) { (_: Progress) -> Void in }
} }
@@ -642,7 +639,7 @@ public extension DataStack {
operations.forEach { migrationOperation.addDependency($0) } operations.forEach { migrationOperation.addDependency($0) }
migrationOperation.addExecutionBlock { () -> Void in migrationOperation.addExecutionBlock { () -> Void in
GCDQueue.main.async { DispatchQueue.main.async {
progress.setProgressHandler(nil) progress.setProgressHandler(nil)
completion(migrationResult ?? MigrationResult(migrationTypes)) completion(migrationResult ?? MigrationResult(migrationTypes))
@@ -752,7 +749,7 @@ public extension DataStack {
) )
let temporaryFileURL = try! temporaryDirectoryURL.appendingPathComponent( let temporaryFileURL = try! temporaryDirectoryURL.appendingPathComponent(
fileURL.lastPathComponent!, fileURL.lastPathComponent,
isDirectory: false isDirectory: false
) )
@@ -766,11 +763,11 @@ public extension DataStack {
try migrationManager.migrateStore( try migrationManager.migrateStore(
from: fileURL, from: fileURL,
sourceType: storage.dynamicType.storeType, sourceType: type(of: storage).storeType,
options: nil, options: nil,
with: mappingModel, with: mappingModel,
toDestinationURL: temporaryFileURL, toDestinationURL: temporaryFileURL,
destinationType: storage.dynamicType.storeType, destinationType: type(of: storage).storeType,
destinationOptions: nil destinationOptions: nil
) )
} }
+6 -6
View File
@@ -60,7 +60,7 @@ import CoreData
- a version appears twice as a key in a dictionary literal - a version appears twice as a key in a dictionary literal
- a loop is found in any of the paths - a loop is found in any of the paths
*/ */
public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible, Equatable { public struct MigrationChain: ExpressibleByNilLiteral, ExpressibleByStringLiteral, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral, Equatable {
/** /**
Initializes the `MigrationChain` with empty values, which instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable progressive migrations. Initializes the `MigrationChain` with empty values, which instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable progressive migrations.
@@ -87,7 +87,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
/** /**
Initializes the `MigrationChain` with a linear order of versions, which becomes the order of the `DataStack`'s progressive migrations. Initializes the `MigrationChain` with a linear order of versions, which becomes the order of the `DataStack`'s progressive migrations.
*/ */
public init<T: Collection where T.Iterator.Element == String, T.SubSequence.Iterator.Element == String, T.Index: Comparable>(_ elements: T) { public init<T: Collection>(_ elements: T) where T.Iterator.Element == String, T.SubSequence.Iterator.Element == String, T.Index: Comparable {
CoreStore.assert(Set(elements).count == Array(elements).count, "\(cs_typeName(MigrationChain.self))'s migration chain could not be created due to duplicate version strings.") CoreStore.assert(Set(elements).count == Array(elements).count, "\(cs_typeName(MigrationChain.self))'s migration chain could not be created due to duplicate version strings.")
@@ -168,7 +168,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
} }
// MARK: NilLiteralConvertible // MARK: ExpressibleByNilLiteral
public init(nilLiteral: ()) { public init(nilLiteral: ()) {
@@ -176,7 +176,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
} }
// MARK: StringLiteralConvertible // MARK: ExpressibleByStringLiteral
public init(stringLiteral value: String) { public init(stringLiteral value: String) {
@@ -200,7 +200,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
} }
// MARK: DictionaryLiteralConvertible // MARK: ExpressibleByDictionaryLiteral
public init(dictionaryLiteral elements: (String, String)...) { public init(dictionaryLiteral elements: (String, String)...) {
@@ -208,7 +208,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
} }
// MARK: ArrayLiteralConvertible // MARK: ExpressibleByArrayLiteral
public init(arrayLiteral elements: String...) { public init(arrayLiteral elements: String...) {
+7 -6
View File
@@ -57,7 +57,7 @@ import Foundation
} }
``` ```
*/ */
public enum MigrationResult: Boolean, Hashable { public enum MigrationResult: Hashable {
/** /**
`MigrationResult.success` indicates either the migration succeeded, or there were no migrations needed. The associated value is an array of `MigrationType`s reflecting the migration steps completed. `MigrationResult.success` indicates either the migration succeeded, or there were no migrations needed. The associated value is an array of `MigrationType`s reflecting the migration steps completed.
@@ -70,9 +70,10 @@ public enum MigrationResult: Boolean, Hashable {
case failure(CoreStoreError) case failure(CoreStoreError)
// MARK: BooleanType /**
Returns `true` if the result indicates `.success`, `false` if the result is `.failure`.
public var boolValue: Bool { */
public var isSuccess: Bool {
switch self { switch self {
@@ -90,7 +91,7 @@ public enum MigrationResult: Boolean, Hashable {
case .success(let migrationTypes): case .success(let migrationTypes):
return self.boolValue.hashValue return self.boolValue.hashValue
^ migrationTypes.map { $0.hashValue }.reduce(0, combine: ^).hashValue ^ migrationTypes.map { $0.hashValue }.reduce(0, ^).hashValue
case .failure(let error): case .failure(let error):
return self.boolValue.hashValue ^ error.hashValue return self.boolValue.hashValue ^ error.hashValue
@@ -110,7 +111,7 @@ public enum MigrationResult: Boolean, Hashable {
self = .failure(error) self = .failure(error)
} }
internal init(_ error: ErrorProtocol) { internal init(_ error: Error) {
self = .failure(CoreStoreError(error)) self = .failure(CoreStoreError(error))
} }
+5 -5
View File
@@ -31,7 +31,7 @@ import Foundation
/** /**
The `MigrationType` specifies the type of migration required for a store. The `MigrationType` specifies the type of migration required for a store.
*/ */
public enum MigrationType: Boolean, Hashable { public enum MigrationType: Hashable {
/** /**
Indicates that the persistent store matches the latest model version and no migration is needed Indicates that the persistent store matches the latest model version and no migration is needed
@@ -108,10 +108,10 @@ public enum MigrationType: Boolean, Hashable {
return false return false
} }
/**
// MARK: BooleanType Returns `true` if the `MigrationType` is either a lightweight or a heavyweight migration. Returns `false` if no migrations specified.
*/
public var boolValue: Bool { public var hasMigration: Bool {
switch self { switch self {
+6 -5
View File
@@ -60,7 +60,7 @@ import CoreData
) )
``` ```
*/ */
public enum SetupResult<T: StorageInterface>: Boolean, Hashable { public enum SetupResult<T: StorageInterface>: Hashable {
/** /**
`SetupResult.success` indicates that the storage setup succeeded. The associated object for this `enum` value is the related `StorageInterface` instance. `SetupResult.success` indicates that the storage setup succeeded. The associated object for this `enum` value is the related `StorageInterface` instance.
@@ -73,9 +73,10 @@ public enum SetupResult<T: StorageInterface>: Boolean, Hashable {
case failure(CoreStoreError) case failure(CoreStoreError)
// MARK: BooleanType /**
Returns `true` if the result indicates `.success`, `false` if the result is `.failure`.
public var boolValue: Bool { */
public var isSuccess: Bool {
switch self { switch self {
@@ -112,7 +113,7 @@ public enum SetupResult<T: StorageInterface>: Boolean, Hashable {
self = .failure(error) self = .failure(error)
} }
internal init(_ error: ErrorProtocol) { internal init(_ error: Error) {
self = .failure(CoreStoreError(error)) self = .failure(CoreStoreError(error))
} }
@@ -43,11 +43,11 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
- parameter completion: the block executed after the save completes. Success or failure is reported by the `CSSaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `CSSaveResult` argument of the block.
*/ */
@objc @objc
public func commitWithCompletion(_ completion: ((result: CSSaveResult) -> Void)?) { public func commitWithCompletion(_ completion: ((_ result: CSSaveResult) -> Void)?) {
self.bridgeToSwift.commit { (result) in self.bridgeToSwift.commit { (result) in
completion?(result: result.bridgeToObjectiveC) completion?(result.bridgeToObjectiveC)
} }
} }
@@ -59,7 +59,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
*/ */
@objc @objc
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? { public func beginSynchronous(_ closure: @escaping (_ transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge { return bridge {
@@ -75,7 +75,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
@@ -266,7 +266,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
return ObjectIdentifier(self.bridgeToSwift).hashValue return ObjectIdentifier(self.bridgeToSwift).hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSBaseDataTransaction else { guard let object = object as? CSBaseDataTransaction else {
@@ -36,11 +36,11 @@ public extension CSCoreStore {
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
@objc @objc
public static func beginAsynchronous(_ closure: (transaction: CSAsynchronousDataTransaction) -> Void) { public static func beginAsynchronous(_ closure: @escaping (_ transaction: CSAsynchronousDataTransaction) -> Void) {
return CoreStore.beginAsynchronous { (transaction) in return CoreStore.beginAsynchronous { (transaction) in
closure(transaction: transaction.bridgeToObjectiveC) closure(transaction.bridgeToObjectiveC)
} }
} }
@@ -52,7 +52,7 @@ public extension CSCoreStore {
*/ */
@objc @objc
@discardableResult @discardableResult
public static func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? { public static func beginSynchronous(_ closure: @escaping (_ transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge { return bridge {
@@ -36,11 +36,11 @@ public extension CSDataStack {
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
@objc @objc
public func beginAsynchronous(_ closure: (transaction: CSAsynchronousDataTransaction) -> Void) { public func beginAsynchronous(_ closure: @escaping (_ transaction: CSAsynchronousDataTransaction) -> Void) {
return self.bridgeToSwift.beginAsynchronous { (transaction) in return self.bridgeToSwift.beginAsynchronous { (transaction) in
closure(transaction: transaction.bridgeToObjectiveC) closure(transaction.bridgeToObjectiveC)
} }
} }
@@ -52,7 +52,7 @@ public extension CSDataStack {
*/ */
@objc @objc
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? { public func beginSynchronous(_ closure: @escaping (_ transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge { return bridge {
+2 -2
View File
@@ -244,7 +244,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
return ObjectIdentifier(self.bridgeToSwift).hashValue return ObjectIdentifier(self.bridgeToSwift).hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSDataStack else { guard let object = object as? CSDataStack else {
@@ -255,7 +255,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+10 -10
View File
@@ -53,7 +53,7 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSError else { guard let object = object as? CSError else {
@@ -64,7 +64,7 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
@@ -150,27 +150,27 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
case .differentStorageExistsAtURL(let existingPersistentStoreURL): case .differentStorageExistsAtURL(let existingPersistentStoreURL):
code = .differentStorageExistsAtURL code = .differentStorageExistsAtURL
info = [ info = [
"existingPersistentStoreURL": existingPersistentStoreURL "existingPersistentStoreURL" as NSObject: existingPersistentStoreURL as AnyObject
] ]
case .mappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion): case .mappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
code = .mappingModelNotFound code = .mappingModelNotFound
info = [ info = [
"localStoreURL": localStoreURL, "localStoreURL" as NSObject: localStoreURL as AnyObject,
"targetModel": targetModel, "targetModel" as NSObject: targetModel,
"targetModelVersion": targetModelVersion "targetModelVersion" as NSObject: targetModelVersion as AnyObject
] ]
case .progressiveMigrationRequired(let localStoreURL): case .progressiveMigrationRequired(let localStoreURL):
code = .progressiveMigrationRequired code = .progressiveMigrationRequired
info = [ info = [
"localStoreURL": localStoreURL "localStoreURL" as NSObject: localStoreURL as AnyObject
] ]
case .internalError(let NSError): case .internalError(let NSError):
code = .internalError code = .internalError
info = [ info = [
"NSError": NSError "NSError" as NSObject: NSError
] ]
} }
@@ -242,7 +242,7 @@ extension CoreStoreError: CoreStoreSwiftType {
// MARK: Internal // MARK: Internal
internal extension ErrorProtocol { internal extension Error {
internal var bridgeToSwift: CoreStoreError { internal var bridgeToSwift: CoreStoreError {
@@ -254,7 +254,7 @@ internal extension ErrorProtocol {
case let error as CSError: case let error as CSError:
return error.bridgeToSwift return error.bridgeToSwift
case let error as NSError where self.dynamicType is NSError.Type: case let error as NSError where type(of: self) is NSError.Type:
return .internalError(NSError: error) return .internalError(NSError: error)
default: default:
+1 -1
View File
@@ -136,7 +136,7 @@ public final class CSFrom: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -76,7 +76,7 @@ public final class CSGroupBy: NSObject, CSQueryClause, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSGroupBy else { guard let object = object as? CSGroupBy else {
@@ -87,7 +87,7 @@ public final class CSGroupBy: NSObject, CSQueryClause, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -92,7 +92,7 @@ public final class CSInMemoryStore: NSObject, CSStorageInterface, CoreStoreObjec
return ObjectIdentifier(self.bridgeToSwift).hashValue return ObjectIdentifier(self.bridgeToSwift).hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSInMemoryStore else { guard let object = object as? CSInMemoryStore else {
@@ -103,7 +103,7 @@ public final class CSInMemoryStore: NSObject, CSStorageInterface, CoreStoreObjec
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -93,7 +93,7 @@ public final class CSInto: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSInto else { guard let object = object as? CSInto else {
@@ -104,7 +104,7 @@ public final class CSInto: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -513,7 +513,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSListMonitor else { guard let object = object as? CSListMonitor else {
@@ -524,7 +524,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+9 -9
View File
@@ -90,15 +90,15 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (migrationTypes: [CSMigrationType]) -> Void, failure: @noescape (error: NSError) -> Void) { public func handleSuccess(_ success: (_ migrationTypes: [CSMigrationType]) -> Void, failure: (_ error: NSError) -> Void) {
switch self.bridgeToSwift { switch self.bridgeToSwift {
case .success(let migrationTypes): case .success(let migrationTypes):
success(migrationTypes: migrationTypes.map { $0.bridgeToObjectiveC }) success(migrationTypes.map { $0.bridgeToObjectiveC })
case .failure(let error): case .failure(let error):
failure(error: error.bridgeToObjectiveC) failure(error.bridgeToObjectiveC)
} }
} }
@@ -110,13 +110,13 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
- parameter success: the block to execute on success. The block passes an array of `CSMigrationType`s that indicates the migration steps completed. - parameter success: the block to execute on success. The block passes an array of `CSMigrationType`s that indicates the migration steps completed.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (migrationTypes: [CSMigrationType]) -> Void) { public func handleSuccess(_ success: (_ migrationTypes: [CSMigrationType]) -> Void) {
guard case .success(let migrationTypes) = self.bridgeToSwift else { guard case .success(let migrationTypes) = self.bridgeToSwift else {
return return
} }
success(migrationTypes: migrationTypes.map { $0.bridgeToObjectiveC }) success(migrationTypes.map { $0.bridgeToObjectiveC })
} }
/** /**
@@ -127,13 +127,13 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleFailure(_ failure: @noescape (error: NSError) -> Void) { public func handleFailure(_ failure: (_ error: NSError) -> Void) {
guard case .failure(let error) = self.bridgeToSwift else { guard case .failure(let error) = self.bridgeToSwift else {
return return
} }
failure(error: error.bridgeToObjectiveC) failure(error.bridgeToObjectiveC)
} }
@@ -144,7 +144,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSMigrationResult else { guard let object = object as? CSMigrationResult else {
@@ -155,7 +155,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -90,7 +90,7 @@ public final class CSMigrationType: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSMigrationType else { guard let object = object as? CSMigrationType else {
@@ -101,7 +101,7 @@ public final class CSMigrationType: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -107,7 +107,7 @@ public final class CSObjectMonitor: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSObjectMonitor else { guard let object = object as? CSObjectMonitor else {
@@ -118,7 +118,7 @@ public final class CSObjectMonitor: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -84,7 +84,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSOrderBy else { guard let object = object as? CSOrderBy else {
@@ -95,7 +95,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -170,7 +170,7 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
return ObjectIdentifier(self.bridgeToSwift).hashValue return ObjectIdentifier(self.bridgeToSwift).hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSSQLiteStore else { guard let object = object as? CSSQLiteStore else {
@@ -181,7 +181,7 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+9 -9
View File
@@ -90,15 +90,15 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (hasChanges: Bool) -> Void, failure: @noescape (error: NSError) -> Void) { public func handleSuccess(_ success: (_ hasChanges: Bool) -> Void, failure: (_ error: NSError) -> Void) {
switch self.bridgeToSwift { switch self.bridgeToSwift {
case .success(let hasChanges): case .success(let hasChanges):
success(hasChanges: hasChanges) success(hasChanges)
case .failure(let error): case .failure(let error):
failure(error: error.bridgeToObjectiveC) failure(error.bridgeToObjectiveC)
} }
} }
@@ -110,13 +110,13 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
- parameter success: the block to execute on success. The block passes a `BOOL` argument that indicates if there were any changes made. - parameter success: the block to execute on success. The block passes a `BOOL` argument that indicates if there were any changes made.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (hasChanges: Bool) -> Void) { public func handleSuccess(_ success: (_ hasChanges: Bool) -> Void) {
guard case .success(let hasChanges) = self.bridgeToSwift else { guard case .success(let hasChanges) = self.bridgeToSwift else {
return return
} }
success(hasChanges: hasChanges) success(hasChanges)
} }
/** /**
@@ -127,13 +127,13 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleFailure(_ failure: @noescape (error: NSError) -> Void) { public func handleFailure(_ failure: (_ error: NSError) -> Void) {
guard case .failure(let error) = self.bridgeToSwift else { guard case .failure(let error) = self.bridgeToSwift else {
return return
} }
failure(error: error.bridgeToObjectiveC) failure(error.bridgeToObjectiveC)
} }
@@ -144,7 +144,7 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSSaveResult else { guard let object = object as? CSSaveResult else {
@@ -155,7 +155,7 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -59,7 +59,7 @@ public final class CSSectionBy: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSectionBy` clause with the key path to use to group `CSListMonitor` objects into sections - returns: a `CSSectionBy` clause with the key path to use to group `CSListMonitor` objects into sections
*/ */
@objc @objc
public static func keyPath(_ sectionKeyPath: KeyPath, sectionIndexTransformer: (sectionName: String?) -> String?) -> CSSectionBy { public static func keyPath(_ sectionKeyPath: KeyPath, sectionIndexTransformer: (_ sectionName: String?) -> String?) -> CSSectionBy {
return self.init(SectionBy(sectionKeyPath, sectionIndexTransformer)) return self.init(SectionBy(sectionKeyPath, sectionIndexTransformer))
} }
@@ -69,7 +69,7 @@ public final class CSSectionBy: NSObject, CoreStoreObjectiveCType {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+4 -4
View File
@@ -164,7 +164,7 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSSelectTerm else { guard let object = object as? CSSelectTerm else {
@@ -335,10 +335,10 @@ public final class CSSelect: NSObject {
public override var hash: Int { public override var hash: Int {
return self.attributeType.hashValue return self.attributeType.hashValue
^ self.selectTerms.map { $0.hashValue }.reduce(0, combine: ^) ^ self.selectTerms.map { $0.hashValue }.reduce(0, ^)
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSSelect else { guard let object = object as? CSSelect else {
@@ -350,7 +350,7 @@ public final class CSSelect: NSObject {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+10 -10
View File
@@ -76,15 +76,15 @@ public final class CSSetupResult: NSObject {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (storage: CSStorageInterface) -> Void, failure: @noescape (error: NSError) -> Void) { public func handleSuccess(_ success: (_ storage: CSStorageInterface) -> Void, failure: (_ error: NSError) -> Void) {
if let storage = self.storage { if let storage = self.storage {
success(storage: storage) success(storage)
} }
else { else {
failure(error: self.error!) failure(self.error!)
} }
} }
@@ -96,13 +96,13 @@ public final class CSSetupResult: NSObject {
- parameter success: the block to execute on success. The block passes a `BOOL` argument that indicates if there were any changes made. - parameter success: the block to execute on success. The block passes a `BOOL` argument that indicates if there were any changes made.
*/ */
@objc @objc
public func handleSuccess(_ success: @noescape (storage: CSStorageInterface) -> Void) { public func handleSuccess(_ success: (_ storage: CSStorageInterface) -> Void) {
guard let storage = self.storage else { guard let storage = self.storage else {
return return
} }
success(storage: storage) success(storage)
} }
/** /**
@@ -113,13 +113,13 @@ public final class CSSetupResult: NSObject {
- parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error. - parameter failure: the block to execute on failure. The block passes an `NSError` argument that pertains to the actual error.
*/ */
@objc @objc
public func handleFailure(_ failure: @noescape (error: NSError) -> Void) { public func handleFailure(_ failure: (_ error: NSError) -> Void) {
guard let error = self.error else { guard let error = self.error else {
return return
} }
failure(error: error) failure(error)
} }
@@ -134,7 +134,7 @@ public final class CSSetupResult: NSObject {
return self.isSuccess.hashValue ^ self.error!.hashValue return self.isSuccess.hashValue ^ self.error!.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSSetupResult else { guard let object = object as? CSSetupResult else {
@@ -146,13 +146,13 @@ public final class CSSetupResult: NSObject {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
// MARK: CoreStoreObjectiveCType // MARK: CoreStoreObjectiveCType
public required init<T: StorageInterface where T: CoreStoreSwiftType, T.ObjectiveCType: CSStorageInterface>(_ swiftValue: SetupResult<T>) { public required init<T: StorageInterface>(_ swiftValue: SetupResult<T>) where T: CoreStoreSwiftType, T.ObjectiveCType: CSStorageInterface {
switch swiftValue { switch swiftValue {
@@ -59,7 +59,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
*/ */
@objc @objc
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? { public func beginSynchronous(_ closure: @escaping (_ transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge { return bridge {
@@ -75,7 +75,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+3 -3
View File
@@ -41,7 +41,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
The block to customize the `NSFetchRequest` The block to customize the `NSFetchRequest`
*/ */
@objc @objc
public var block: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void { public var block: (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void {
return self.bridgeToSwift.closure return self.bridgeToSwift.closure
} }
@@ -53,7 +53,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
- parameter block: the block to customize the `NSFetchRequest` - parameter block: the block to customize the `NSFetchRequest`
*/ */
@objc @objc
public convenience init(block: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) { public convenience init(block: (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) {
self.init(Tweak(block)) self.init(Tweak(block))
} }
@@ -63,7 +63,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
@@ -43,11 +43,11 @@ public final class CSUnsafeDataTransaction: CSBaseDataTransaction {
- parameter completion: the block executed after the save completes. Success or failure is reported by the `CSSaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `CSSaveResult` argument of the block.
*/ */
@objc @objc
public func commit(_ completion: ((result: CSSaveResult) -> Void)?) { public func commit(_ completion: ((_ result: CSSaveResult) -> Void)?) {
self.bridgeToSwift.commit { (result) in self.bridgeToSwift.commit { (result) in
completion?(result: result.bridgeToObjectiveC) completion?(result.bridgeToObjectiveC)
} }
} }
@@ -166,7 +166,7 @@ public final class CSUnsafeDataTransaction: CSBaseDataTransaction {
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+2 -2
View File
@@ -121,7 +121,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
return self.bridgeToSwift.hashValue return self.bridgeToSwift.hashValue
} }
public override func isEqual(_ object: AnyObject?) -> Bool { public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSWhere else { guard let object = object as? CSWhere else {
@@ -132,7 +132,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
public override var description: String { public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
} }
+8 -8
View File
@@ -79,17 +79,17 @@ public extension CoreStoreSwiftType where ObjectiveCType: CoreStoreObjectiveCTyp
// MARK: - Internal // MARK: - Internal
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(_ closure: @noescape () -> T) -> T.ObjectiveCType { internal func bridge<T: CoreStoreSwiftType>(_ closure: () -> T) -> T.ObjectiveCType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType {
return closure().bridgeToObjectiveC return closure().bridgeToObjectiveC
} }
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(_ closure: @noescape () -> T?) -> T.ObjectiveCType? { internal func bridge<T: CoreStoreSwiftType>(_ closure: () -> T?) -> T.ObjectiveCType? where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType {
return closure()?.bridgeToObjectiveC return closure()?.bridgeToObjectiveC
} }
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(_ closure: @noescape () throws -> T) throws -> T.ObjectiveCType { internal func bridge<T: CoreStoreSwiftType>(_ closure: () throws -> T) throws -> T.ObjectiveCType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType {
do { do {
@@ -101,7 +101,7 @@ internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObje
} }
} }
internal func bridge(_ closure: @noescape () throws -> Void) throws { internal func bridge(_ closure: () throws -> Void) throws {
do { do {
@@ -113,7 +113,7 @@ internal func bridge(_ closure: @noescape () throws -> Void) throws {
} }
} }
internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, _ closure: @noescape () throws -> T) -> T.ObjectiveCType? { internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, _ closure: () throws -> T) -> T.ObjectiveCType? {
do { do {
@@ -128,7 +128,7 @@ internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, _ closure:
} }
} }
internal func bridge(_ error: NSErrorPointer, _ closure: @noescape () throws -> Void) -> Bool { internal func bridge(_ error: NSErrorPointer, _ closure: () throws -> Void) -> Bool {
do { do {
@@ -143,7 +143,7 @@ internal func bridge(_ error: NSErrorPointer, _ closure: @noescape () throws ->
} }
} }
internal func bridge<T>(_ error: NSErrorPointer, _ closure: @noescape () throws -> T?) -> T? { internal func bridge<T>(_ error: NSErrorPointer, _ closure: () throws -> T?) -> T? {
do { do {
@@ -158,7 +158,7 @@ internal func bridge<T>(_ error: NSErrorPointer, _ closure: @noescape () throws
} }
} }
internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, _ closure: @noescape () throws -> [T]) -> [T.ObjectiveCType]? { internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, _ closure: () throws -> [T]) -> [T.ObjectiveCType]? {
do { do {
@@ -36,7 +36,7 @@ public extension Progress {
- parameter closure: the closure to execute on progress change - parameter closure: the closure to execute on progress change
*/ */
@objc @objc
public func cs_setProgressHandler(_ closure: ((progress: Progress) -> Void)?) { public func cs_setProgressHandler(_ closure: ((_ progress: Progress) -> Void)?) {
self.setProgressHandler(closure) self.setProgressHandler(closure)
} }
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
#if os(iOS) || os(watchOS) || os(tvOS) #if os(iOS) || os(watchOS) || os(tvOS)
+28 -35
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
#if os(iOS) || os(watchOS) || os(tvOS) #if os(iOS) || os(watchOS) || os(tvOS)
@@ -191,7 +188,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
*/ */
public func hasObjectsInSection(_ section: Int) -> Bool { public func hasObjectsInSection(_ section: Int) -> Bool {
return self.numberOfObjectsInSection(safeSectionIndex: section) > 0 return self.numberOfObjectsInSection(safeSectionIndex: section)! > 0
} }
/** /**
@@ -406,7 +403,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter observer: a `ListObserver` to send change notifications to - parameter observer: a `ListObserver` to send change notifications to
*/ */
public func addObserver<U: ListObserver where U.ListEntityType == T>(_ observer: U) { public func addObserver<U: ListObserver>(_ observer: U) where U.ListEntityType == T {
self.unregisterObserver(observer) self.unregisterObserver(observer)
self.registerObserver( self.registerObserver(
@@ -441,7 +438,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter observer: a `ListObjectObserver` to send change notifications to - parameter observer: a `ListObjectObserver` to send change notifications to
*/ */
public func addObserver<U: ListObjectObserver where U.ListEntityType == T>(_ observer: U) { public func addObserver<U: ListObjectObserver>(_ observer: U) where U.ListEntityType == T {
self.unregisterObserver(observer) self.unregisterObserver(observer)
self.registerObserver( self.registerObserver(
@@ -495,7 +492,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter observer: a `ListSectionObserver` to send change notifications to - parameter observer: a `ListSectionObserver` to send change notifications to
*/ */
public func addObserver<U: ListSectionObserver where U.ListEntityType == T>(_ observer: U) { public func addObserver<U: ListSectionObserver>(_ observer: U) where U.ListEntityType == T {
self.unregisterObserver(observer) self.unregisterObserver(observer)
self.registerObserver( self.registerObserver(
@@ -556,7 +553,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter observer: a `ListObserver` to unregister notifications to - parameter observer: a `ListObserver` to unregister notifications to
*/ */
public func removeObserver<U: ListObserver where U.ListEntityType == T>(_ observer: U) { public func removeObserver<U: ListObserver>(_ observer: U) where U.ListEntityType == T {
self.unregisterObserver(observer) self.unregisterObserver(observer)
} }
@@ -607,7 +604,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
// MARK: Internal // MARK: Internal
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) { internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
self.init( self.init(
context: dataStack.mainContext, context: dataStack.mainContext,
@@ -619,7 +616,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) { internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) {
self.init( self.init(
context: dataStack.mainContext, context: dataStack.mainContext,
@@ -631,7 +628,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) { internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
self.init( self.init(
context: unsafeTransaction.context, context: unsafeTransaction.context,
@@ -643,7 +640,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) { internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) {
self.init( self.init(
context: unsafeTransaction.context, context: unsafeTransaction.context,
@@ -660,7 +657,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
return unsafeBitCast(self, to: ListMonitor<NSManagedObject>.self) return unsafeBitCast(self, to: ListMonitor<NSManagedObject>.self)
} }
internal func registerChangeNotification(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>) -> Void) { internal func registerChangeNotification(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ListMonitor<T>) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -672,7 +669,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
return return
} }
callback(monitor: self) callback(self)
} }
), ),
forKey: notificationKey, forKey: notificationKey,
@@ -680,7 +677,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal func registerObjectNotification(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, object: T, indexPath: IndexPath?, newIndexPath: IndexPath?) -> Void) { internal func registerObjectNotification(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ListMonitor<T>, _ object: T, _ indexPath: IndexPath?, _ newIndexPath: IndexPath?) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -695,10 +692,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
return return
} }
callback( callback(
monitor: self, self,
object: object, object,
indexPath: userInfo[String(IndexPath.self)] as? IndexPath, userInfo[String(IndexPath.self)] as? IndexPath,
newIndexPath: userInfo["\(String(IndexPath.self)).New"] as? IndexPath userInfo["\(String(IndexPath.self)).New"] as? IndexPath
) )
} }
), ),
@@ -707,7 +704,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal func registerSectionNotification(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, sectionIndex: Int) -> Void) { internal func registerSectionNotification(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ListMonitor<T>, _ sectionInfo: NSFetchedResultsSectionInfo, _ sectionIndex: Int) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -722,11 +719,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
return return
} }
callback( callback(self, sectionInfo, sectionIndex)
monitor: self,
sectionInfo: sectionInfo,
sectionIndex: sectionIndex
)
} }
), ),
forKey: notificationKey, forKey: notificationKey,
@@ -734,7 +727,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal func registerObserver<U: AnyObject>(_ observer: U, willChange: (observer: U, monitor: ListMonitor<T>) -> Void, didChange: (observer: U, monitor: ListMonitor<T>) -> Void, willRefetch: (observer: U, monitor: ListMonitor<T>) -> Void, didRefetch: (observer: U, monitor: ListMonitor<T>) -> Void) { internal func registerObserver<U: AnyObject>(_ observer: U, willChange: @escaping (_ observer: U, _ monitor: ListMonitor<T>) -> Void, didChange: @escaping (_ observer: U, _ monitor: ListMonitor<T>) -> Void, willRefetch: @escaping (_ observer: U, _ monitor: ListMonitor<T>) -> Void, didRefetch: @escaping (_ observer: U, _ monitor: ListMonitor<T>) -> Void) {
CoreStore.assert( CoreStore.assert(
Thread.isMainThread, Thread.isMainThread,
@@ -794,7 +787,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal func registerObserver<U: AnyObject>(_ observer: U, didInsertObject: (observer: U, monitor: ListMonitor<T>, object: T, toIndexPath: IndexPath) -> Void, didDeleteObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: IndexPath) -> Void, didUpdateObject: (observer: U, monitor: ListMonitor<T>, object: T, atIndexPath: IndexPath) -> Void, didMoveObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: IndexPath, toIndexPath: IndexPath) -> Void) { internal func registerObserver<U: AnyObject>(_ observer: U, didInsertObject: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ object: T, _ toIndexPath: IndexPath) -> Void, didDeleteObject: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ object: T, _ fromIndexPath: IndexPath) -> Void, didUpdateObject: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ object: T, _ atIndexPath: IndexPath) -> Void, didMoveObject: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ object: T, _ fromIndexPath: IndexPath, _ toIndexPath: IndexPath) -> Void) {
CoreStore.assert( CoreStore.assert(
Thread.isMainThread, Thread.isMainThread,
@@ -876,7 +869,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
) )
} }
internal func registerObserver<U: AnyObject>(_ observer: U, didInsertSection: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, toIndex: Int) -> Void, didDeleteSection: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, fromIndex: Int) -> Void) { internal func registerObserver<U: AnyObject>(_ observer: U, didInsertSection: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ sectionInfo: NSFetchedResultsSectionInfo, _ toIndex: Int) -> Void, didDeleteSection: @escaping (_ observer: U, _ monitor: ListMonitor<T>, _ sectionInfo: NSFetchedResultsSectionInfo, _ fromIndex: Int) -> Void) {
CoreStore.assert( CoreStore.assert(
Thread.isMainThread, Thread.isMainThread,
@@ -942,7 +935,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
cs_setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteSectionKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteSectionKey, inObject: observer)
} }
internal func refetch(_ applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) { internal func refetch(_ applyFetchClauses: @escaping (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
CoreStore.assert( CoreStore.assert(
Thread.isMainThread, Thread.isMainThread,
@@ -979,7 +972,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
try! self.fetchedResultsController.performFetchFromSpecifiedStores() try! self.fetchedResultsController.performFetchFromSpecifiedStores()
GCDQueue.main.async { [weak self] () -> Void in DispatchQueue.main.async { [weak self] () -> Void in
guard let `self` = self else { guard let `self` = self else {
@@ -1022,12 +1015,12 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
private let fetchedResultsController: CoreStoreFetchedResultsController private let fetchedResultsController: CoreStoreFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<T> private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<T>
private let sectionIndexTransformer: (sectionName: KeyPath?) -> String? private let sectionIndexTransformer: (_ sectionName: KeyPath?) -> String?
private var observerForWillChangePersistentStore: NotificationObserver! private var observerForWillChangePersistentStore: NotificationObserver!
private var observerForDidChangePersistentStore: NotificationObserver! private var observerForDidChangePersistentStore: NotificationObserver!
private let taskGroup = GCDGroup() private let taskGroup = DispatchGroup()
private let transactionQueue: GCDQueue private let transactionQueue: DispatchQueue
private var applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void private var applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void
private var isPersistentStoreChanging: Bool = false { private var isPersistentStoreChanging: Bool = false {
@@ -1050,7 +1043,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
} }
} }
private init(context: NSManagedObjectContext, transactionQueue: GCDQueue, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: ((ListMonitor<T>) -> Void)?) { private init(context: NSManagedObjectContext, transactionQueue: DispatchQueue, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (_ fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: ((ListMonitor<T>) -> Void)?) {
let fetchRequest = CoreStoreFetchRequest<T>() let fetchRequest = CoreStoreFetchRequest<T>()
fetchRequest.fetchLimit = 0 fetchRequest.fetchLimit = 0
+17 -25
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
#if os(iOS) || os(watchOS) || os(tvOS) #if os(iOS) || os(watchOS) || os(tvOS)
@@ -73,7 +70,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
- parameter observer: an `ObjectObserver` to send change notifications to - parameter observer: an `ObjectObserver` to send change notifications to
*/ */
public func addObserver<U: ObjectObserver where U.ObjectEntityType == EntityType>(_ observer: U) { public func addObserver<U: ObjectObserver>(_ observer: U) where U.ObjectEntityType == EntityType {
self.unregisterObserver(observer) self.unregisterObserver(observer)
self.registerObserver( self.registerObserver(
@@ -100,7 +97,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
- parameter observer: an `ObjectObserver` to unregister notifications to - parameter observer: an `ObjectObserver` to unregister notifications to
*/ */
public func removeObserver<U: ObjectObserver where U.ObjectEntityType == EntityType>(_ observer: U) { public func removeObserver<U: ObjectObserver>(_ observer: U) where U.ObjectEntityType == EntityType {
self.unregisterObserver(observer) self.unregisterObserver(observer)
} }
@@ -126,7 +123,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
self.init(context: unsafeTransaction.context, object: object) self.init(context: unsafeTransaction.context, object: object)
} }
internal func registerObserver<U: AnyObject>(_ observer: U, willChangeObject: (observer: U, monitor: ObjectMonitor<EntityType>, object: EntityType) -> Void, didDeleteObject: (observer: U, monitor: ObjectMonitor<EntityType>, object: EntityType) -> Void, didUpdateObject: (observer: U, monitor: ObjectMonitor<EntityType>, object: EntityType, changedPersistentKeys: Set<String>) -> Void) { internal func registerObserver<U: AnyObject>(_ observer: U, willChangeObject: @escaping (_ observer: U, _ monitor: ObjectMonitor<EntityType>, _ object: EntityType) -> Void, didDeleteObject: @escaping (_ observer: U, _ monitor: ObjectMonitor<EntityType>, _ object: EntityType) -> Void, didUpdateObject: @escaping (_ observer: U, _ monitor: ObjectMonitor<EntityType>, _ object: EntityType, _ changedPersistentKeys: Set<String>) -> Void) {
CoreStore.assert( CoreStore.assert(
Thread.isMainThread, Thread.isMainThread,
@@ -142,7 +139,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
return return
} }
willChangeObject(observer: observer, monitor: monitor, object: object) willChangeObject(observer, monitor, object)
} }
) )
self.registerObjectNotification( self.registerObjectNotification(
@@ -155,7 +152,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
return return
} }
didDeleteObject(observer: observer, monitor: monitor, object: object) didDeleteObject(observer, monitor, object)
} }
) )
self.registerObjectNotification( self.registerObjectNotification(
@@ -182,12 +179,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
} }
self.lastCommittedAttributes = currentCommitedAttributes self.lastCommittedAttributes = currentCommitedAttributes
didUpdateObject( didUpdateObject(observer, monitor, object, changedKeys)
observer: observer,
monitor: monitor,
object: object,
changedPersistentKeys: changedKeys
)
} }
) )
} }
@@ -255,7 +247,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
self.lastCommittedAttributes = (self.object?.committedValues(forKeys: nil) as? [String: NSObject]) ?? [:] self.lastCommittedAttributes = (self.object?.committedValues(forKeys: nil) as? [String: NSObject]) ?? [:]
} }
private func registerChangeNotification(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<EntityType>) -> Void) { private func registerChangeNotification(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ObjectMonitor<EntityType>) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -267,7 +259,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
return return
} }
callback(monitor: self) callback(self)
} }
), ),
forKey: notificationKey, forKey: notificationKey,
@@ -275,7 +267,7 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
) )
} }
private func registerObjectNotification(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<EntityType>, object: EntityType) -> Void) { private func registerObjectNotification(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ObjectMonitor<EntityType>, _ object: EntityType) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -285,11 +277,11 @@ public final class ObjectMonitor<EntityType: NSManagedObject> {
guard let `self` = self, guard let `self` = self,
let userInfo = note.userInfo, let userInfo = note.userInfo,
let object = userInfo[String(NSManagedObject.self)] as? EntityType else { let object = userInfo[String(describing: NSManagedObject.self)] as? EntityType else {
return return
} }
callback(monitor: self, object: object) callback(self, object)
} }
), ),
forKey: notificationKey, forKey: notificationKey,
@@ -338,7 +330,7 @@ extension ObjectMonitor: FetchedResultsControllerHandler {
NotificationCenter.default.post( NotificationCenter.default.post(
name: Notification.Name.objectMonitorDidDeleteObject, name: Notification.Name.objectMonitorDidDeleteObject,
object: self, object: self,
userInfo: [String(NSManagedObject.self): anObject] userInfo: [String(describing: NSManagedObject.self): anObject]
) )
case .update, case .update,
@@ -346,7 +338,7 @@ extension ObjectMonitor: FetchedResultsControllerHandler {
NotificationCenter.default.post( NotificationCenter.default.post(
name: Notification.Name.objectMonitorDidUpdateObject, name: Notification.Name.objectMonitorDidUpdateObject,
object: self, object: self,
userInfo: [String(NSManagedObject.self): anObject] userInfo: [String(describing: NSManagedObject.self): anObject]
) )
default: default:
@@ -365,11 +357,11 @@ extension ObjectMonitor: FetchedResultsControllerHandler {
// MARK: - Notification.Name // MARK: - Notification.Name
private extension Notification.Name { fileprivate extension Notification.Name {
private static let objectMonitorWillChangeObject = Notification.Name(rawValue: "objectMonitorWillChangeObject") fileprivate static let objectMonitorWillChangeObject = Notification.Name(rawValue: "objectMonitorWillChangeObject")
private static let objectMonitorDidDeleteObject = Notification.Name(rawValue: "objectMonitorDidDeleteObject") fileprivate static let objectMonitorDidDeleteObject = Notification.Name(rawValue: "objectMonitorDidDeleteObject")
private static let objectMonitorDidUpdateObject = Notification.Name(rawValue: "objectMonitorDidUpdateObject") fileprivate static let objectMonitorDidUpdateObject = Notification.Name(rawValue: "objectMonitorDidUpdateObject")
} }
#endif #endif
+2 -2
View File
@@ -60,7 +60,7 @@ public struct SectionBy {
- parameter sectionKeyPath: the key path to use to group the objects into sections - parameter sectionKeyPath: the key path to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section name - parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section name
*/ */
public init(_ sectionKeyPath: KeyPath, _ sectionIndexTransformer: (sectionName: String?) -> String?) { public init(_ sectionKeyPath: KeyPath, _ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?) {
self.sectionKeyPath = sectionKeyPath self.sectionKeyPath = sectionKeyPath
self.sectionIndexTransformer = sectionIndexTransformer self.sectionIndexTransformer = sectionIndexTransformer
@@ -70,7 +70,7 @@ public struct SectionBy {
// MARK: Internal // MARK: Internal
internal let sectionKeyPath: KeyPath internal let sectionKeyPath: KeyPath
internal let sectionIndexTransformer: (sectionName: KeyPath?) -> String? internal let sectionIndexTransformer: (_ sectionName: KeyPath?) -> String?
} }
#endif #endif
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
#if os(iOS) || os(watchOS) || os(tvOS) #if os(iOS) || os(watchOS) || os(tvOS)
+2 -5
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - CoreStore // MARK: - CoreStore
@@ -81,7 +78,7 @@ public extension CoreStore {
- returns: the `StorageInterface` added to the `defaultStack` - returns: the `StorageInterface` added to the `defaultStack`
*/ */
@discardableResult @discardableResult
public static func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type) throws -> T { public static func addStorageAndWait<T: StorageInterface>(_ storeType: T.Type) throws -> T where T: DefaultInitializableStore {
return try self.defaultStack.addStorageAndWait(storeType.init()) return try self.defaultStack.addStorageAndWait(storeType.init())
} }
@@ -111,7 +108,7 @@ public extension CoreStore {
- returns: the local storage added to the `defaultStack` - returns: the local storage added to the `defaultStack`
*/ */
@discardableResult @discardableResult
public static func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(_ storageType: T.Type) throws -> T { public static func addStorageAndWait<T: LocalStorage>(_ storageType: T.Type) throws -> T where T: DefaultInitializableStore {
return try self.defaultStack.addStorageAndWait(storageType.init()) return try self.defaultStack.addStorageAndWait(storageType.init())
} }
+18 -15
View File
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - DataStack // MARK: - DataStack
@@ -135,7 +132,7 @@ public final class DataStack {
- returns: the `StorageInterface` added to the stack - returns: the `StorageInterface` added to the stack
*/ */
@discardableResult @discardableResult
public func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type) throws -> T { public func addStorageAndWait<T: StorageInterface>(_ storeType: T.Type) throws -> T where T: DefaultInitializableStore {
return try self.addStorageAndWait(storeType.init()) return try self.addStorageAndWait(storeType.init())
} }
@@ -189,7 +186,7 @@ public final class DataStack {
- returns: the local storage added to the stack - returns: the local storage added to the stack
*/ */
@discardableResult @discardableResult
public func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(_ storageType: T.Type) throws -> T { public func addStorageAndWait<T: LocalStorage>(_ storageType: T.Type) throws -> T where T: DefaultInitializableStore {
return try self.addStorageAndWait(storageType.init()) return try self.addStorageAndWait(storageType.init())
} }
@@ -258,7 +255,7 @@ public final class DataStack {
catch let error as NSError where storage.localStorageOptions.contains(.recreateStoreOnModelMismatch) && error.isCoreDataMigrationError { catch let error as NSError where storage.localStorageOptions.contains(.recreateStoreOnModelMismatch) && error.isCoreDataMigrationError {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: fileURL, at: fileURL,
options: storeOptions options: storeOptions
) )
@@ -353,7 +350,7 @@ public final class DataStack {
catch let error as NSError where storage.cloudStorageOptions.contains(.recreateLocalStoreOnModelMismatch) && error.isCoreDataMigrationError { catch let error as NSError where storage.cloudStorageOptions.contains(.recreateLocalStoreOnModelMismatch) && error.isCoreDataMigrationError {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
at: cacheFileURL, at: cacheFileURL,
options: storeOptions options: storeOptions
) )
@@ -381,22 +378,28 @@ public final class DataStack {
// MARK: Internal // MARK: Internal
internal static let applicationName = (Bundle.main.objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData" internal static let applicationName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "CoreData"
internal let coordinator: NSPersistentStoreCoordinator internal let coordinator: NSPersistentStoreCoordinator
internal let rootSavingContext: NSManagedObjectContext internal let rootSavingContext: NSManagedObjectContext
internal let mainContext: NSManagedObjectContext internal let mainContext: NSManagedObjectContext
internal let model: NSManagedObjectModel internal let model: NSManagedObjectModel
internal let migrationChain: MigrationChain internal let migrationChain: MigrationChain
internal let childTransactionQueue = GCDQueue.createSerial("com.coreStore.dataStack.childTransactionQueue") internal let childTransactionQueue = DispatchQueue(serialWith: "com.coreStore.dataStack.childTransactionQueue")
internal let storeMetadataUpdateQueue = GCDQueue.createConcurrent("com.coreStore.persistentStoreBarrierQueue") internal let storeMetadataUpdateQueue = DispatchQueue(concurrentWith: "com.coreStore.persistentStoreBarrierQueue")
internal let migrationQueue: OperationQueue = { internal let migrationQueue: OperationQueue = {
let migrationQueue = OperationQueue() let migrationQueue = OperationQueue()
migrationQueue.maxConcurrentOperationCount = 1 migrationQueue.maxConcurrentOperationCount = 1
migrationQueue.name = "com.coreStore.migrationOperationQueue" migrationQueue.name = "com.coreStore.migrationOperationQueue"
migrationQueue.qualityOfService = .utility migrationQueue.qualityOfService = .utility
migrationQueue.underlyingQueue = GCDQueue.createSerial("com.coreStore.migrationQueue").dispatchQueue() migrationQueue.underlyingQueue = DispatchQueue(
label: "com.coreStore.migrationQueue",
qos: .userInitiated,
attributes: .allZeros,
autoreleaseFrequency: .workItem,
target: nil
)
return migrationQueue return migrationQueue
}() }()
@@ -415,7 +418,7 @@ public final class DataStack {
internal func persistentStoresForEntityClass(_ entityClass: AnyClass) -> [NSPersistentStore]? { internal func persistentStoresForEntityClass(_ entityClass: AnyClass) -> [NSPersistentStore]? {
var returnValue: [NSPersistentStore]? = nil var returnValue: [NSPersistentStore]? = nil
self.storeMetadataUpdateQueue.barrierSync { self.storeMetadataUpdateQueue.sync(flags: .barrier) {
returnValue = self.entityConfigurationsMapping[NSStringFromClass(entityClass)]?.map { returnValue = self.entityConfigurationsMapping[NSStringFromClass(entityClass)]?.map {
@@ -428,7 +431,7 @@ public final class DataStack {
internal func persistentStoreForEntityClass(_ entityClass: AnyClass, configuration: String?, inferStoreIfPossible: Bool) -> (store: NSPersistentStore?, isAmbiguous: Bool) { internal func persistentStoreForEntityClass(_ entityClass: AnyClass, configuration: String?, inferStoreIfPossible: Bool) -> (store: NSPersistentStore?, isAmbiguous: Bool) {
var returnValue: (store: NSPersistentStore?, isAmbiguous: Bool) = (store: nil, isAmbiguous: false) var returnValue: (store: NSPersistentStore?, isAmbiguous: Bool) = (store: nil, isAmbiguous: false)
self.storeMetadataUpdateQueue.barrierSync { self.storeMetadataUpdateQueue.sync(flags: .barrier) {
let configurationsForEntity = self.entityConfigurationsMapping[NSStringFromClass(entityClass)] ?? [] let configurationsForEntity = self.entityConfigurationsMapping[NSStringFromClass(entityClass)] ?? []
if let configuration = configuration { if let configuration = configuration {
@@ -462,14 +465,14 @@ public final class DataStack {
internal func createPersistentStoreFromStorage(_ storage: StorageInterface, finalURL: URL?, finalStoreOptions: [String: AnyObject]?) throws -> NSPersistentStore { internal func createPersistentStoreFromStorage(_ storage: StorageInterface, finalURL: URL?, finalStoreOptions: [String: AnyObject]?) throws -> NSPersistentStore {
let persistentStore = try self.coordinator.addPersistentStore( let persistentStore = try self.coordinator.addPersistentStore(
ofType: storage.dynamicType.storeType, ofType: type(of: storage).storeType,
configurationName: storage.configuration, configurationName: storage.configuration,
at: finalURL, at: finalURL,
options: finalStoreOptions options: finalStoreOptions
) )
persistentStore.storageInterface = storage persistentStore.storageInterface = storage
self.storeMetadataUpdateQueue.barrierAsync { self.storeMetadataUpdateQueue.async(flags: .barrier) {
let configurationName = persistentStore.configurationName let configurationName = persistentStore.configurationName
self.configurationStoreMapping[configurationName] = persistentStore self.configurationStoreMapping[configurationName] = persistentStore
@@ -434,9 +434,9 @@ public class ICloudStore: CloudStorage {
let options = [ let options = [
NSSQLitePragmasOption: ["journal_mode": "DELETE"], NSSQLitePragmasOption: ["journal_mode": "DELETE"],
NSPersistentStoreRemoveUbiquitousMetadataOption: true NSPersistentStoreRemoveUbiquitousMetadataOption: true
] ] as [String : Any]
let store = try journalUpdatingCoordinator.addPersistentStore( let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType, ofType: type(of: self).storeType,
configurationName: self.configuration, configurationName: self.configuration,
at: cacheFileURL, at: cacheFileURL,
options: options options: options
@@ -470,7 +470,7 @@ public class ICloudStore: CloudStorage {
private weak var dataStack: DataStack? private weak var dataStack: DataStack?
private func registerNotification<T: ICloudStoreObserver>(_ notificationKey: UnsafePointer<Void>, name: Notification.Name, toObserver observer: T, callback: (observer: T, storage: ICloudStore, dataStack: DataStack) -> Void) { private func registerNotification<T: ICloudStoreObserver>(_ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: T, callback: @escaping (_ observer: T, _ storage: ICloudStore, _ dataStack: DataStack) -> Void) {
cs_setAssociatedRetainedObject( cs_setAssociatedRetainedObject(
NotificationObserver( NotificationObserver(
@@ -485,7 +485,7 @@ public class ICloudStore: CloudStorage {
return return
} }
callback(observer: observer, storage: self, dataStack: dataStack) callback(observer, self, dataStack)
} }
), ),
forKey: notificationKey, forKey: notificationKey,
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - LegacySQLiteStore // MARK: - LegacySQLiteStore
@@ -177,7 +174,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel) let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStore( let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType, ofType: type(of: self).storeType,
configurationName: self.configuration, configurationName: self.configuration,
at: fileURL, at: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]] options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
@@ -197,7 +194,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
attributes: nil attributes: nil
) )
try fileManager.moveItem(at: fileURL, to: temporaryFile) try fileManager.moveItem(at: fileURL, to: temporaryFile)
GCDQueue.background.async { DispatchQueue.global(qos: .background).async {
_ = try? fileManager.removeItem(at: temporaryFile) _ = try? fileManager.removeItem(at: temporaryFile)
} }
@@ -24,9 +24,6 @@
// //
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - SQLiteStore // MARK: - SQLiteStore
@@ -174,7 +171,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel) let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStore( let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType, ofType: type(of: self).storeType,
configurationName: self.configuration, configurationName: self.configuration,
at: fileURL, at: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]] options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
@@ -194,7 +191,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
attributes: nil attributes: nil
) )
try fileManager.moveItem(at: fileURL, to: temporaryFile) try fileManager.moveItem(at: fileURL, to: temporaryFile)
GCDQueue.background.async { DispatchQueue.global(qos: .background).async {
_ = try? fileManager.removeItem(at: temporaryFile) _ = try? fileManager.removeItem(at: temporaryFile)
} }
@@ -226,9 +223,9 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
) )
}() }()
internal static let defaultFileURL = try! SQLiteStore.defaultRootDirectory internal static let defaultFileURL = SQLiteStore.defaultRootDirectory
.appendingPathComponent( .appendingPathComponent(
(Bundle.main.objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData", (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "CoreData",
isDirectory: false isDirectory: false
) )
.appendingPathExtension("sqlite") .appendingPathExtension("sqlite")
@@ -82,7 +82,7 @@ public protocol DefaultInitializableStore: StorageInterface {
/** /**
The `LocalStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers. The `LocalStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers.
*/ */
public struct LocalStorageOptions: OptionSet, NilLiteralConvertible { public struct LocalStorageOptions: OptionSet, ExpressibleByNilLiteral {
/** /**
Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch
@@ -119,7 +119,7 @@ public struct LocalStorageOptions: OptionSet, NilLiteralConvertible {
public let rawValue: Int public let rawValue: Int
// MARK: NilLiteralConvertible // MARK: ExpressibleByNilLiteral
public init(nilLiteral: ()) { public init(nilLiteral: ()) {
@@ -165,7 +165,7 @@ internal extension LocalStorage {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool { internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
return persistentStore.type == self.dynamicType.storeType return persistentStore.type == type(of: self).storeType
&& persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName) && persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName)
&& persistentStore.url == self.fileURL && persistentStore.url == self.fileURL
} }
@@ -177,7 +177,7 @@ internal extension LocalStorage {
/** /**
The `CloudStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers. The `CloudStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers.
*/ */
public struct CloudStorageOptions: OptionSet, NilLiteralConvertible { public struct CloudStorageOptions: OptionSet, ExpressibleByNilLiteral {
/** /**
Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch
@@ -208,7 +208,7 @@ public struct CloudStorageOptions: OptionSet, NilLiteralConvertible {
public let rawValue: Int public let rawValue: Int
// MARK: NilLiteralConvertible // MARK: ExpressibleByNilLiteral
public init(nilLiteral: ()) { public init(nilLiteral: ()) {
@@ -249,7 +249,7 @@ internal extension CloudStorage {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool { internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
guard persistentStore.type == self.dynamicType.storeType guard persistentStore.type == type(of: self).storeType
&& persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName) else { && persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName) else {
return false return false
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - AsynchronousDataTransaction // MARK: - AsynchronousDataTransaction
@@ -42,7 +39,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block.
*/ */
public func commit(_ completion: (result: SaveResult) -> Void = { _ in }) { public func commit(_ completion: @escaping (_ result: SaveResult) -> Void = { _ in }) {
CoreStore.assert( CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(), self.transactionQueue.isCurrentExecutionContext(),
@@ -54,12 +51,12 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
) )
self.isCommitted = true self.isCommitted = true
let group = GCDGroup() let group = DispatchGroup()
group.enter() group.enter()
self.context.saveAsynchronouslyWithCompletion { (result) -> Void in self.context.saveAsynchronouslyWithCompletion { (result) -> Void in
self.result = result self.result = result
completion(result: result) completion(result)
group.leave() group.leave()
} }
group.wait() group.wait()
@@ -72,7 +69,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public func beginSynchronous(_ closure: (_ transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert( CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(), self.transactionQueue.isCurrentExecutionContext(),
@@ -178,7 +175,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter objects: the `NSManagedObject`s type to be deleted - parameter objects: the `NSManagedObject`s type to be deleted
*/ */
public override func delete<S: Sequence where S.Iterator.Element: NSManagedObject>(_ objects: S) { public override func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: NSManagedObject {
CoreStore.assert( CoreStore.assert(
!self.isCommitted, !self.isCommitted,
@@ -191,7 +188,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
// MARK: Internal // MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, closure: (transaction: AsynchronousDataTransaction) -> Void) { internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue, closure: (_ transaction: AsynchronousDataTransaction) -> Void) {
self.closure = closure self.closure = closure
@@ -233,5 +230,5 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
// MARK: Private // MARK: Private
private let closure: (transaction: AsynchronousDataTransaction) -> Void private let closure: (_ transaction: AsynchronousDataTransaction) -> Void
} }
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - BaseDataTransaction // MARK: - BaseDataTransaction
@@ -87,7 +84,7 @@ public /*abstract*/ class BaseDataTransaction {
switch context.parentStack!.persistentStoreForEntityClass( switch context.parentStack!.persistentStoreForEntityClass(
entityClass, entityClass,
configuration: into.configuration configuration: into.configuration
?? into.dynamicType.defaultConfigurationName, ?? type(of: into).defaultConfigurationName,
inferStoreIfPossible: false inferStoreIfPossible: false
) { ) {
@@ -187,7 +184,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter objects: the `NSManagedObject`s to be deleted - parameter objects: the `NSManagedObject`s to be deleted
*/ */
public func delete<S: Sequence where S.Iterator.Element: NSManagedObject>(_ objects: S) { public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: NSManagedObject {
CoreStore.assert( CoreStore.assert(
self.isRunningInAllowedQueue(), self.isRunningInAllowedQueue(),
@@ -453,8 +450,8 @@ public /*abstract*/ class BaseDataTransaction {
// MARK: Internal // MARK: Internal
internal let context: NSManagedObjectContext internal let context: NSManagedObjectContext
internal let transactionQueue: GCDQueue internal let transactionQueue: DispatchQueue
internal let childTransactionQueue = GCDQueue.createSerial("com.corestore.datastack.childtransactionqueue") internal let childTransactionQueue = DispatchQueue(serialWith: "com.corestore.datastack.childtransactionqueue")
internal let supportsUndo: Bool internal let supportsUndo: Bool
internal let bypassesQueueing: Bool internal let bypassesQueueing: Bool
@@ -462,7 +459,7 @@ public /*abstract*/ class BaseDataTransaction {
internal var isCommitted = false internal var isCommitted = false
internal var result: SaveResult? internal var result: SaveResult?
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool, bypassesQueueing: Bool) { internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue, supportsUndo: Bool, bypassesQueueing: Bool) {
let context = mainContext.temporaryContextInTransactionWithConcurrencyType( let context = mainContext.temporaryContextInTransactionWithConcurrencyType(
queue == .main queue == .main
@@ -35,7 +35,7 @@ public extension CoreStore {
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
public static func beginAsynchronous(_ closure: (transaction: AsynchronousDataTransaction) -> Void) { public static func beginAsynchronous(_ closure: (_ transaction: AsynchronousDataTransaction) -> Void) {
self.defaultStack.beginAsynchronous(closure) self.defaultStack.beginAsynchronous(closure)
} }
@@ -47,7 +47,7 @@ public extension CoreStore {
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
@discardableResult @discardableResult
public static func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public static func beginSynchronous(_ closure: (_ transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
return self.defaultStack.beginSynchronous(closure) return self.defaultStack.beginSynchronous(closure)
} }
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - DataStack // MARK: - DataStack
@@ -39,7 +36,7 @@ public extension DataStack {
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
public func beginAsynchronous(_ closure: (transaction: AsynchronousDataTransaction) -> Void) { public func beginAsynchronous(_ closure: (_ transaction: AsynchronousDataTransaction) -> Void) {
AsynchronousDataTransaction( AsynchronousDataTransaction(
mainContext: self.rootSavingContext, mainContext: self.rootSavingContext,
@@ -54,7 +51,7 @@ public extension DataStack {
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public func beginSynchronous(_ closure: (_ transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
return SynchronousDataTransaction( return SynchronousDataTransaction(
mainContext: self.rootSavingContext, mainContext: self.rootSavingContext,
+13 -15
View File
@@ -70,6 +70,19 @@ public enum SaveResult: Hashable {
case failure(CoreStoreError) case failure(CoreStoreError)
/**
Returns `true` if the result indicates `.success`, `false` if the result is `.failure`.
*/
public var boolValue: Bool {
switch self {
case .success: return true
case .failure: return false
}
}
// MARK: Hashable // MARK: Hashable
public var hashValue: Int { public var hashValue: Int {
@@ -99,21 +112,6 @@ public enum SaveResult: Hashable {
} }
// MARK: - SaveResult: BooleanType
extension SaveResult: Boolean {
public var boolValue: Bool {
switch self {
case .success: return true
case .failure: return false
}
}
}
// MARK: - SaveResult: Equatable // MARK: - SaveResult: Equatable
public func == (lhs: SaveResult, rhs: SaveResult) -> Bool { public func == (lhs: SaveResult, rhs: SaveResult) -> Bool {
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - SynchronousDataTransaction // MARK: - SynchronousDataTransaction
@@ -67,7 +64,7 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
@discardableResult @discardableResult
public func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public func beginSynchronous(_ closure: (_ transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert( CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(), self.transactionQueue.isCurrentExecutionContext(),
@@ -173,7 +170,7 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
- parameter objects: the `NSManagedObject`s to be deleted - parameter objects: the `NSManagedObject`s to be deleted
*/ */
public override func delete<S: Sequence where S.Iterator.Element: NSManagedObject>(_ objects: S) { public override func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: NSManagedObject {
CoreStore.assert( CoreStore.assert(
!self.isCommitted, !self.isCommitted,
@@ -186,7 +183,7 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
// MARK: Internal // MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, closure: (transaction: SynchronousDataTransaction) -> Void) { internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue, closure: (_ transaction: SynchronousDataTransaction) -> Void) {
self.closure = closure self.closure = closure
@@ -213,5 +210,5 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
// MARK: Private // MARK: Private
private let closure: (transaction: SynchronousDataTransaction) -> Void private let closure: (_ transaction: SynchronousDataTransaction) -> Void
} }
@@ -25,9 +25,6 @@
import Foundation import Foundation
import CoreData import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - UnsafeDataTransaction // MARK: - UnsafeDataTransaction
@@ -42,12 +39,12 @@ public final class UnsafeDataTransaction: BaseDataTransaction {
- parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block.
*/ */
public func commit(_ completion: (result: SaveResult) -> Void) { public func commit(_ completion: @escaping (_ result: SaveResult) -> Void) {
self.context.saveAsynchronouslyWithCompletion { (result) -> Void in self.context.saveAsynchronouslyWithCompletion { (result) -> Void in
self.result = result self.result = result
completion(result: result) completion(result)
} }
} }
@@ -105,7 +102,7 @@ public final class UnsafeDataTransaction: BaseDataTransaction {
- parameter closure: the closure where changes can be made prior to the flush - parameter closure: the closure where changes can be made prior to the flush
- throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors) - throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors)
*/ */
public func flush(closure: @noescape () throws -> Void) rethrows { public func flush(closure: () throws -> Void) rethrows {
try closure() try closure()
self.context.processPendingChanges() self.context.processPendingChanges()
@@ -153,7 +150,7 @@ public final class UnsafeDataTransaction: BaseDataTransaction {
// MARK: Internal // MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool) { internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue, supportsUndo: Bool) {
super.init(mainContext: mainContext, queue: queue, supportsUndo: supportsUndo, bypassesQueueing: true) super.init(mainContext: mainContext, queue: queue, supportsUndo: supportsUndo, bypassesQueueing: true)
} }