WIP: segfault

This commit is contained in:
John Rommel Estropia
2016-07-20 08:12:04 +09:00
parent f486ace437
commit 267c21063a
129 changed files with 2205 additions and 3282 deletions
@@ -26,198 +26,199 @@
import Foundation
import CoreData
#if os(iOS) || os(watchOS) || os(tvOS)
// MARK: - NSFetchedResultsController
public extension NSFetchedResultsController {
/**
Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter dataStack: the `DataStack` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes a `DataStack`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(dataStack: DataStack, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
return self.createFromContext(
dataStack.mainContext,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: sectionBy,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter dataStack: the `DataStack` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes a `DataStack`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(dataStack: DataStack, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return self.createFromContext(
dataStack.mainContext,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: sectionBy,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter dataStack: the `DataStack` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes a `DataStack`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(dataStack: DataStack, _ from: From<T>, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
return self.createFromContext(
dataStack.mainContext,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: nil,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter dataStack: the `DataStack` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes a `DataStack`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(dataStack: DataStack, _ from: From<T>, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return self.createFromContext(
dataStack.mainContext,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: nil,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter transaction: the `UnsafeDataTransaction` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(transaction: UnsafeDataTransaction, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
return self.createFromContext(
transaction.context,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: sectionBy,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter transaction: the `UnsafeDataTransaction` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(transaction: UnsafeDataTransaction, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return self.createFromContext(
transaction.context,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: sectionBy,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter transaction: the `UnsafeDataTransaction` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
*/
@nonobjc
public static func createFor<T: NSManagedObject>(transaction: UnsafeDataTransaction, _ from: From<T>, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
return self.createFromContext(
transaction.context,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: nil,
fetchClauses: fetchClauses
)
}
/**
Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
- parameter transaction: the `UnsafeDataTransaction` to observe objects from
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
@nonobjc
public static func createFor<T: NSManagedObject>(transaction: UnsafeDataTransaction, _ from: From<T>, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return self.createFromContext(
transaction.context,
fetchRequest: CoreStoreFetchRequest(),
from: from,
sectionBy: nil,
fetchClauses: fetchClauses
)
}
// MARK: Internal
@nonobjc
internal static func createFromContext<T: NSManagedObject>(context: NSManagedObjectContext, fetchRequest: NSFetchRequest, from: From<T>? = nil, sectionBy: SectionBy? = nil, fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return CoreStoreFetchedResultsController(
context: context,
fetchRequest: fetchRequest,
from: from,
sectionBy: sectionBy,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor."
)
}
)
}
}
#endif
// TODO: Uncomment
//#if os(iOS) || os(watchOS) || os(tvOS)
//
//// MARK: - NSFetchedResultsController
//
//public extension NSFetchedResultsController {
//
// /**
// Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter dataStack: the `DataStack` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes a `DataStack`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ dataStack: DataStack, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController<NSFetchRequestResult> {
//
// return self.createFromContext(
// dataStack.mainContext,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: sectionBy,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter dataStack: the `DataStack` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes a `DataStack`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ dataStack: DataStack, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
//
// return self.createFromContext(
// dataStack.mainContext,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: sectionBy,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter dataStack: the `DataStack` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes a `DataStack`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ dataStack: DataStack, _ from: From<T>, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
//
// return self.createFromContext(
// dataStack.mainContext,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: nil,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter dataStack: the `DataStack` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes a `DataStack`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ dataStack: DataStack, _ from: From<T>, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
//
// return self.createFromContext(
// dataStack.mainContext,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: nil,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter transaction: the `UnsafeDataTransaction` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ transaction: UnsafeDataTransaction, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
//
// return self.createFromContext(
// transaction.context,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: sectionBy,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter transaction: the `UnsafeDataTransaction` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ transaction: UnsafeDataTransaction, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
//
// return self.createFromContext(
// transaction.context,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: sectionBy,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter transaction: the `UnsafeDataTransaction` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// - returns: an `NSFetchedResultsController` that observes an `UnsafeDataTransaction`
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ transaction: UnsafeDataTransaction, _ from: From<T>, _ fetchClauses: FetchClause...) -> NSFetchedResultsController {
//
// return self.createFromContext(
// transaction.context,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: nil,
// fetchClauses: fetchClauses
// )
// }
//
// /**
// Utility for creating an `NSFetchedResultsController` from an `UnsafeDataTransaction`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `ListMonitor`s abstraction.
//
// - parameter transaction: the `UnsafeDataTransaction` to observe objects from
// - parameter from: a `From` clause indicating the entity type
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
// */
// @nonobjc
// public static func createFor<T: NSManagedObject>(_ transaction: UnsafeDataTransaction, _ from: From<T>, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController {
//
// return self.createFromContext(
// transaction.context,
// fetchRequest: CoreStoreFetchRequest(),
// from: from,
// sectionBy: nil,
// fetchClauses: fetchClauses
// )
// }
//
//
// // MARK: Internal
//
// @nonobjc
// internal static func createFromContext<T: NSManagedObject>(_ context: NSManagedObjectContext, fetchRequest: CoreStoreFetchRequest<T>, from: From<T>? = nil, sectionBy: SectionBy? = nil, fetchClauses: [FetchClause]) -> NSFetchedResultsController<NSFetchRequestResult> {
//
// let controller = CoreStoreFetchedResultsController(
// context: context,
// fetchRequest: fetchRequest,
// from: from,
// sectionBy: sectionBy,
// applyFetchClauses: { fetchRequest in
//
// fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
//
// CoreStore.assert(
// fetchRequest.sortDescriptors?.isEmpty == false,
// "An \(cs_typeName(NSFetchedResultsController<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor."
// )
// }
// )
// return controller.upcast()
// }
//}
//
//#endif
@@ -39,11 +39,11 @@ public extension NSManagedObject {
*/
@nonobjc
@warn_unused_result
public func accessValueForKVCKey(KVCKey: KeyPath) -> AnyObject? {
public func accessValueForKVCKey(_ KVCKey: KeyPath) -> AnyObject? {
self.willAccessValueForKey(KVCKey)
let primitiveValue: AnyObject? = self.primitiveValueForKey(KVCKey)
self.didAccessValueForKey(KVCKey)
self.willAccessValue(forKey: KVCKey)
let primitiveValue: AnyObject? = self.primitiveValue(forKey: KVCKey)
self.didAccessValue(forKey: KVCKey)
return primitiveValue
}
@@ -55,11 +55,11 @@ public extension NSManagedObject {
- parameter KVCKey: the KVC key
*/
@nonobjc
public func setValue(value: AnyObject?, forKVCKey KVCKey: KeyPath) {
public func setValue(_ value: AnyObject?, forKVCKey KVCKey: KeyPath) {
self.willChangeValueForKey(KVCKey)
self.willChangeValue(forKey: KVCKey)
self.setPrimitiveValue(value, forKey: KVCKey)
self.didChangeValueForKey(KVCKey)
self.didChangeValue(forKey: KVCKey)
}
/**
@@ -68,7 +68,7 @@ public extension NSManagedObject {
@nonobjc
public func refreshAsFault() {
self.managedObjectContext?.refreshObject(self, mergeChanges: false)
self.managedObjectContext?.refresh(self, mergeChanges: false)
}
/**
@@ -77,6 +77,6 @@ public extension NSManagedObject {
@nonobjc
public func refreshAndMerge() {
self.managedObjectContext?.refreshObject(self, mergeChanges: true)
self.managedObjectContext?.refresh(self, mergeChanges: true)
}
}
@@ -31,7 +31,7 @@ import Foundation
// MARK: - NSProgress
public extension NSProgress {
public extension Progress {
/**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
@@ -39,7 +39,7 @@ public extension NSProgress {
- parameter closure: the closure to execute on progress change
*/
@nonobjc
public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
public func setProgressHandler(_ closure: ((progress: Progress) -> Void)?) {
self.progressObserver.progressHandler = closure
}
@@ -81,8 +81,8 @@ public extension NSProgress {
@objc
private final class ProgressObserver: NSObject {
private unowned let progress: NSProgress
private var progressHandler: ((progress: NSProgress) -> Void)? {
private unowned let progress: Progress
private var progressHandler: ((progress: Progress) -> Void)? {
didSet {
@@ -97,7 +97,7 @@ private final class ProgressObserver: NSObject {
self.progress.addObserver(
self,
forKeyPath: "fractionCompleted",
options: [.Initial, .New],
options: [.initial, .new],
context: nil
)
}
@@ -108,7 +108,7 @@ private final class ProgressObserver: NSObject {
}
}
private init(_ progress: NSProgress) {
private init(_ progress: Progress) {
self.progress = progress
super.init()
@@ -123,14 +123,14 @@ private final class ProgressObserver: NSObject {
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutablePointer<Void>?) {
guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else {
guard let progress = object as? Progress where progress == self.progress && keyPath == "fractionCompleted" else {
return
}
GCDQueue.Main.async { [weak self] () -> Void in
GCDQueue.main.async { [weak self] () -> Void in
self?.progressHandler?(progress: progress)
}
+33 -50
View File
@@ -32,32 +32,32 @@ import CoreData
/**
All errors thrown from CoreStore are expressed in `CoreStoreError` enum values.
*/
public enum CoreStoreError: ErrorType, Hashable {
public enum CoreStoreError: ErrorProtocol, Hashable {
/**
A failure occured because of an unknown error.
*/
case Unknown
case unknown
/**
The `NSPersistentStore` could not be initialized because another store existed at the specified `NSURL`.
*/
case DifferentStorageExistsAtURL(existingPersistentStoreURL: NSURL)
case differentStorageExistsAtURL(existingPersistentStoreURL: URL)
/**
An `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case MappingModelNotFound(localStoreURL: NSURL, targetModel: NSManagedObjectModel, targetModelVersion: String)
case mappingModelNotFound(localStoreURL: URL, targetModel: NSManagedObjectModel, targetModelVersion: String)
/**
Progressive migrations are disabled for a store, but an `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case ProgressiveMigrationRequired(localStoreURL: NSURL)
case progressiveMigrationRequired(localStoreURL: URL)
/**
An internal SDK call failed with the specified `NSError`.
*/
case InternalError(NSError: NSError)
case internalError(NSError: NSError)
// MARK: ErrorType
@@ -71,20 +71,20 @@ public enum CoreStoreError: ErrorType, Hashable {
switch self {
case .Unknown:
return CoreStoreErrorCode.UnknownError.rawValue
case .unknown:
return CoreStoreErrorCode.unknownError.rawValue
case .DifferentStorageExistsAtURL:
return CoreStoreErrorCode.DifferentPersistentStoreExistsAtURL.rawValue
case .differentStorageExistsAtURL:
return CoreStoreErrorCode.differentPersistentStoreExistsAtURL.rawValue
case .MappingModelNotFound:
return CoreStoreErrorCode.MappingModelNotFound.rawValue
case .mappingModelNotFound:
return CoreStoreErrorCode.mappingModelNotFound.rawValue
case .ProgressiveMigrationRequired:
return CoreStoreErrorCode.ProgressiveMigrationRequired.rawValue
case .progressiveMigrationRequired:
return CoreStoreErrorCode.progressiveMigrationRequired.rawValue
case .InternalError:
return CoreStoreErrorCode.InternalError.rawValue
case .internalError:
return CoreStoreErrorCode.internalError.rawValue
}
}
@@ -96,19 +96,19 @@ public enum CoreStoreError: ErrorType, Hashable {
let code = self._code
switch self {
case .Unknown:
case .unknown:
return code.hashValue
case .DifferentStorageExistsAtURL(let existingPersistentStoreURL):
case .differentStorageExistsAtURL(let existingPersistentStoreURL):
return code.hashValue ^ existingPersistentStoreURL.hashValue
case .MappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
case .mappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
return code.hashValue ^ localStoreURL.hashValue ^ targetModel.hashValue ^ targetModelVersion.hashValue
case .ProgressiveMigrationRequired(let localStoreURL):
case .progressiveMigrationRequired(let localStoreURL):
return code.hashValue ^ localStoreURL.hashValue
case .InternalError(let NSError):
case .internalError(let NSError):
return code.hashValue ^ NSError.hashValue
}
}
@@ -116,33 +116,32 @@ public enum CoreStoreError: ErrorType, Hashable {
// MARK: Internal
internal init(_ error: ErrorType?) {
internal init(_ error: ErrorProtocol?) {
self = error.flatMap { $0.bridgeToSwift } ?? .Unknown
self = error.flatMap { $0.bridgeToSwift } ?? .unknown
}
}
// MARK: - CoreStoreError: Equatable
@warn_unused_result
public func == (lhs: CoreStoreError, rhs: CoreStoreError) -> Bool {
switch (lhs, rhs) {
case (.Unknown, .Unknown):
case (.unknown, .unknown):
return true
case (.DifferentStorageExistsAtURL(let url1), .DifferentStorageExistsAtURL(let url2)):
case (.differentStorageExistsAtURL(let url1), .differentStorageExistsAtURL(let url2)):
return url1 == url2
case (.MappingModelNotFound(let url1, let model1, let version1), .MappingModelNotFound(let url2, let model2, let version2)):
case (.mappingModelNotFound(let url1, let model1, let version1), .mappingModelNotFound(let url2, let model2, let version2)):
return url1 == url2 && model1 == model2 && version1 == version2
case (.ProgressiveMigrationRequired(let url1), .ProgressiveMigrationRequired(let url2)):
case (.progressiveMigrationRequired(let url1), .progressiveMigrationRequired(let url2)):
return url1 == url2
case (.InternalError(let NSError1), .InternalError(let NSError2)):
case (.internalError(let NSError1), .internalError(let NSError2)):
return NSError1 == NSError2
default:
@@ -170,27 +169,27 @@ public enum CoreStoreErrorCode: Int {
/**
A failure occured because of an unknown error.
*/
case UnknownError
case unknownError
/**
The `NSPersistentStore` could note be initialized because another store existed at the specified `NSURL`.
*/
case DifferentPersistentStoreExistsAtURL
case differentPersistentStoreExistsAtURL
/**
An `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case MappingModelNotFound
case mappingModelNotFound
/**
Progressive migrations are disabled for a store, but an `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case ProgressiveMigrationRequired
case progressiveMigrationRequired
/**
An internal SDK call failed with the specified "NSError" userInfo key.
*/
case InternalError
case internalError
}
@@ -208,20 +207,4 @@ public extension NSError {
|| code == NSMigrationError)
&& self.domain == NSCocoaErrorDomain
}
// MARK: Deprecated
/**
Deprecated. Use `CoreStoreError` enum values instead.
If the error's domain is equal to `CoreStoreErrorDomain`, returns the associated `CoreStoreErrorCode`. For other domains, returns `nil`.
*/
@available(*, deprecated=2.0.0, message="Use CoreStoreError enum values instead.")
public var coreStoreErrorCode: CoreStoreErrorCode? {
return (self.domain == CoreStoreErrorDomain
? CoreStoreErrorCode(rawValue: self.code)
: nil)
}
}
@@ -38,11 +38,11 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject>(object: T) -> T? {
public func fetchExisting<T: NSManagedObject>(_ object: T) -> T? {
do {
return (try self.context.existingObjectWithID(object.objectID) as! T)
return (try self.context.existingObject(with: object.objectID) as! T)
}
catch _ {
@@ -57,11 +57,11 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
public func fetchExisting<T: NSManagedObject>(_ objectID: NSManagedObjectID) -> T? {
do {
return (try self.context.existingObjectWithID(objectID) as! T)
return (try self.context.existingObject(with: objectID) as! T)
}
catch _ {
@@ -76,9 +76,9 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObject` array for objects that exists in the transaction
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] {
return objects.flatMap { (try? self.context.existingObjectWithID($0.objectID)) as? T }
return objects.flatMap { (try? self.context.existingObject(with: $0.objectID)) as? T }
}
/**
@@ -88,9 +88,9 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObject` array for objects that exists in the transaction
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] {
return objectIDs.flatMap { (try? self.context.existingObjectWithID($0)) as? T }
return objectIDs.flatMap { (try? self.context.existingObject(with: $0)) as? T }
}
/**
@@ -101,7 +101,7 @@ public extension BaseDataTransaction {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> T? {
public func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> T? {
return self.fetchOne(from, fetchClauses)
}
@@ -114,7 +114,7 @@ public extension BaseDataTransaction {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
public func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -131,7 +131,7 @@ public extension BaseDataTransaction {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
public func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
return self.fetchAll(from, fetchClauses)
}
@@ -144,7 +144,7 @@ public extension BaseDataTransaction {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
public func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -161,7 +161,7 @@ public extension BaseDataTransaction {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
public func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
return self.fetchCount(from, fetchClauses)
}
@@ -174,7 +174,7 @@ public extension BaseDataTransaction {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
public func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -192,7 +192,7 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
public func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
return self.fetchObjectID(from, fetchClauses)
}
@@ -205,7 +205,7 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
public func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -222,7 +222,7 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
public func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
return self.fetchObjectIDs(from, fetchClauses)
}
@@ -235,7 +235,7 @@ public extension BaseDataTransaction {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
public func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -251,7 +251,7 @@ public extension BaseDataTransaction {
- parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `NSManagedObject`s deleted
*/
public func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: DeleteClause...) -> Int? {
public func deleteAll<T: NSManagedObject>(_ from: From<T>, _ deleteClauses: DeleteClause...) -> Int? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -268,7 +268,7 @@ public extension BaseDataTransaction {
- parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `NSManagedObject`s deleted
*/
public func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: [DeleteClause]) -> Int? {
public func deleteAll<T: NSManagedObject>(_ from: From<T>, _ deleteClauses: [DeleteClause]) -> Int? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -289,7 +289,7 @@ public extension BaseDataTransaction {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -310,7 +310,7 @@ public extension BaseDataTransaction {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -331,7 +331,7 @@ public extension BaseDataTransaction {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
public func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -352,7 +352,7 @@ public extension BaseDataTransaction {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
public func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -58,7 +58,7 @@ public struct From<T: NSManagedObject> {
let people = transaction.fetchAll(From<MyPersonEntity>())
```
*/
public init(){
public init() {
self.init(entityClass: T.self, configurations: nil)
}
@@ -190,7 +190,7 @@ public struct From<T: NSManagedObject> {
// MARK: Internal
@warn_unused_result
internal func applyToFetchRequest(fetchRequest: NSFetchRequest, context: NSManagedObjectContext, applyAffectedStores: Bool = true) -> Bool {
internal func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>, context: NSManagedObjectContext, applyAffectedStores: Bool = true) -> Bool {
fetchRequest.entity = context.entityDescriptionForEntityClass(self.entityClass)
guard applyAffectedStores else {
@@ -202,13 +202,13 @@ public struct From<T: NSManagedObject> {
return true
}
CoreStore.log(
.Warning,
.warning,
message: "Attempted to perform a fetch but could not find any persistent store for the entity \(cs_typeName(fetchRequest.entityName))"
)
return false
}
internal func applyAffectedStoresForFetchedRequest(fetchRequest: NSFetchRequest, context: NSManagedObjectContext) -> Bool {
internal func applyAffectedStoresForFetchedRequest<U: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<U>, context: NSManagedObjectContext) -> Bool {
let stores = self.findPersistentStores(context: context)
fetchRequest.affectedStores = stores
@@ -259,115 +259,4 @@ public struct From<T: NSManagedObject> {
self.configurations = configurations
self.findPersistentStores = findPersistentStores
}
// MARK: Obsolete
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ storeURL: NSURL, _ otherStoreURLs: NSURL...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ storeURLs: [NSURL]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entity: T.Type, _ storeURL: NSURL, _ otherStoreURLs: NSURL...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entity: T.Type, _ storeURLs: [NSURL]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entityClass: AnyClass, _ storeURL: NSURL, _ otherStoreURLs: NSURL...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entityClass: AnyClass, _ storeURLs: [NSURL]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ persistentStore: NSPersistentStore, _ otherPersistentStores: NSPersistentStore...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ persistentStores: [NSPersistentStore]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entity: T.Type, _ persistentStore: NSPersistentStore, _ otherPersistentStores: NSPersistentStore...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entity: T.Type, _ persistentStores: [NSPersistentStore]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entityClass: AnyClass, _ persistentStore: NSPersistentStore, _ otherPersistentStores: NSPersistentStore...) {
CoreStore.abort("Use initializers that accept configuration names.")
}
/**
Obsolete. Use initializers that accept configuration names.
*/
@available(*, obsoleted=2.0.0, message="Use initializers that accept configuration names.")
public init(_ entityClass: AnyClass, _ persistentStores: [NSPersistentStore]) {
CoreStore.abort("Use initializers that accept configuration names.")
}
}
@@ -71,13 +71,13 @@ public struct GroupBy: QueryClause, Hashable {
// MARK: QueryClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
if let keyPaths = fetchRequest.propertiesToGroupBy as? [String] where keyPaths != self.keyPaths {
CoreStore.log(
.Warning,
message: "An existing \"propertiesToGroupBy\" for the \(cs_typeName(NSFetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
.warning,
message: "An existing \"propertiesToGroupBy\" for the \(cs_typeName(NSFetchRequest<ResultType>.self)) was overwritten by \(cs_typeName(self)) query clause."
)
}
@@ -32,7 +32,7 @@ public func +(left: OrderBy, right: OrderBy) -> OrderBy {
return OrderBy(left.sortDescriptors + right.sortDescriptors)
}
public func +=(inout left: OrderBy, right: OrderBy) {
public func +=(left: inout OrderBy, right: OrderBy) {
left = left + right
}
@@ -53,12 +53,12 @@ public enum SortKey {
/**
Indicates that the `KeyPath` should be sorted in ascending order
*/
case Ascending(KeyPath)
case ascending(KeyPath)
/**
Indicates that the `KeyPath` should be sorted in descending order
*/
case Descending(KeyPath)
case descending(KeyPath)
}
@@ -72,14 +72,14 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
/**
The list of sort descriptors
*/
public let sortDescriptors: [NSSortDescriptor]
public let sortDescriptors: [SortDescriptor]
/**
Initializes a `OrderBy` clause with an empty list of sort descriptors
*/
public init() {
self.init([NSSortDescriptor]())
self.init([SortDescriptor]())
}
/**
@@ -87,7 +87,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter sortDescriptor: a `NSSortDescriptor`
*/
public init(_ sortDescriptor: NSSortDescriptor) {
public init(_ sortDescriptor: SortDescriptor) {
self.init([sortDescriptor])
}
@@ -97,7 +97,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter sortDescriptors: a series of `NSSortDescriptor`s
*/
public init(_ sortDescriptors: [NSSortDescriptor]) {
public init(_ sortDescriptors: [SortDescriptor]) {
self.sortDescriptors = sortDescriptors
}
@@ -110,15 +110,15 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
public init(_ sortKey: [SortKey]) {
self.init(
sortKey.map { sortKey -> NSSortDescriptor in
sortKey.map { sortKey -> SortDescriptor in
switch sortKey {
case .Ascending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: true)
case .ascending(let keyPath):
return SortDescriptor(key: keyPath, ascending: true)
case .Descending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: false)
case .descending(let keyPath):
return SortDescriptor(key: keyPath, ascending: false)
}
}
)
@@ -138,13 +138,13 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
// MARK: FetchClause, QueryClause, DeleteClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
if let sortDescriptors = fetchRequest.sortDescriptors where sortDescriptors != self.sortDescriptors {
CoreStore.log(
.Warning,
message: "Existing sortDescriptors for the \(cs_typeName(NSFetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
.warning,
message: "Existing sortDescriptors for the \(cs_typeName(fetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
)
}
@@ -44,7 +44,7 @@ public protocol SelectValueResultType: SelectResultType {
static var attributeType: NSAttributeType { get }
static func fromResultObject(result: AnyObject) -> Self?
static func fromResultObject(_ result: AnyObject) -> Self?
}
@@ -55,7 +55,7 @@ public protocol SelectValueResultType: SelectResultType {
*/
public protocol SelectAttributesResultType: SelectResultType {
static func fromResultObjects(result: [AnyObject]) -> [[NSString: AnyObject]]
static func fromResultObjects(_ result: [AnyObject]) -> [[NSString: AnyObject]]
}
@@ -87,9 +87,9 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter keyPath: the attribute name
- returns: a `SelectTerm` to a `Select` clause for querying an entity attribute
*/
public static func Attribute(keyPath: KeyPath) -> SelectTerm {
public static func attribute(_ keyPath: KeyPath) -> SelectTerm {
return ._Attribute(keyPath)
return ._attribute(keyPath)
}
/**
@@ -105,13 +105,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute
*/
public static func Average(keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
public static func average(_ keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
return ._Aggregate(
return ._aggregate(
function: "average:",
keyPath: keyPath,
alias: alias ?? "average(\(keyPath))",
nativeType: .DecimalAttributeType
nativeType: .decimalAttributeType
)
}
@@ -128,13 +128,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
public static func Count(keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
public static func count(_ keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
return ._Aggregate(
return ._aggregate(
function: "count:",
keyPath: keyPath,
alias: alias ?? "count(\(keyPath))",
nativeType: .Integer64AttributeType
nativeType: .integer64AttributeType
)
}
@@ -151,13 +151,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute
*/
public static func Maximum(keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
public static func maximum(_ keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
return ._Aggregate(
return ._aggregate(
function: "max:",
keyPath: keyPath,
alias: alias ?? "max(\(keyPath))",
nativeType: .UndefinedAttributeType
nativeType: .undefinedAttributeType
)
}
@@ -174,13 +174,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute
*/
public static func Minimum(keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
public static func minimum(_ keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
return ._Aggregate(
return ._aggregate(
function: "min:",
keyPath: keyPath,
alias: alias ?? "min(\(keyPath))",
nativeType: .UndefinedAttributeType
nativeType: .undefinedAttributeType
)
}
@@ -197,13 +197,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func Sum(keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
public static func sum(_ keyPath: KeyPath, As alias: KeyPath? = nil) -> SelectTerm {
return ._Aggregate(
return ._aggregate(
function: "sum:",
keyPath: keyPath,
alias: alias ?? "sum(\(keyPath))",
nativeType: .DecimalAttributeType
nativeType: .decimalAttributeType
)
}
@@ -221,11 +221,11 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "objecID" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func ObjectID(As alias: KeyPath? = nil) -> SelectTerm {
public static func objectID(As alias: KeyPath? = nil) -> SelectTerm {
return ._Identity(
return ._identity(
alias: alias ?? "objectID",
nativeType: .ObjectIDAttributeType
nativeType: .objectIDAttributeType
)
}
@@ -234,17 +234,17 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
public init(stringLiteral value: KeyPath) {
self = ._Attribute(value)
self = ._attribute(value)
}
public init(unicodeScalarLiteral value: KeyPath) {
self = ._Attribute(value)
self = ._attribute(value)
}
public init(extendedGraphemeClusterLiteral value: KeyPath) {
self = ._Attribute(value)
self = ._attribute(value)
}
@@ -254,13 +254,13 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
switch self {
case ._Attribute(let keyPath):
case ._attribute(let keyPath):
return 0 ^ keyPath.hashValue
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
case ._aggregate(let function, let keyPath, let alias, let nativeType):
return 1 ^ function.hashValue ^ keyPath.hashValue ^ alias.hashValue ^ nativeType.hashValue
case ._Identity(let alias, let nativeType):
case ._identity(let alias, let nativeType):
return 3 ^ alias.hashValue ^ nativeType.hashValue
}
}
@@ -268,9 +268,9 @@ public enum SelectTerm: StringLiteralConvertible, Hashable {
// MARK: Internal
case _Attribute(KeyPath)
case _Aggregate(function: String, keyPath: KeyPath, alias: String, nativeType: NSAttributeType)
case _Identity(alias: String, nativeType: NSAttributeType)
case _attribute(KeyPath)
case _aggregate(function: String, keyPath: KeyPath, alias: String, nativeType: NSAttributeType)
case _identity(alias: String, nativeType: NSAttributeType)
}
@@ -281,17 +281,17 @@ public func == (lhs: SelectTerm, rhs: SelectTerm) -> Bool {
switch (lhs, rhs) {
case (._Attribute(let keyPath1), ._Attribute(let keyPath2)):
case (._attribute(let keyPath1), ._attribute(let keyPath2)):
return keyPath1 == keyPath2
case (._Aggregate(let function1, let keyPath1, let alias1, let nativeType1),
._Aggregate(let function2, let keyPath2, let alias2, let nativeType2)):
case (._aggregate(let function1, let keyPath1, let alias1, let nativeType1),
._aggregate(let function2, let keyPath2, let alias2, let nativeType2)):
return function1 == function2
&& keyPath1 == keyPath2
&& alias1 == alias2
&& nativeType1 == nativeType2
case (._Identity(let alias1, let nativeType1), ._Identity(let alias2, let nativeType2)):
case (._identity(let alias1, let nativeType1), ._identity(let alias2, let nativeType2)):
return alias1 == alias2 && nativeType1 == nativeType2
default:
@@ -388,7 +388,7 @@ public extension Select where T: NSManagedObjectID {
public init() {
self.init(.ObjectID())
self.init(.objectID())
}
}
@@ -408,16 +408,16 @@ extension Bool: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .BooleanAttributeType
return .booleanAttributeType
}
public static func fromResultObject(result: AnyObject) -> Bool? {
public static func fromResultObject(_ result: AnyObject) -> Bool? {
switch result {
case let decimal as NSDecimalNumber:
// iOS: NSDecimalNumber(string: "0.5").boolValue // true
// OSX: NSDecimalNumber(string: "0.5").boolValue // false
return NSNumber(double: decimal.doubleValue).boolValue
return NSNumber(value: decimal.doubleValue).boolValue
case let number as NSNumber:
return number.boolValue
@@ -435,12 +435,12 @@ extension Int8: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public static func fromResultObject(result: AnyObject) -> Int8? {
public static func fromResultObject(_ result: AnyObject) -> Int8? {
guard let value = (result as? NSNumber)?.longLongValue else {
guard let value = (result as? NSNumber)?.int64Value else {
return nil
}
@@ -455,12 +455,12 @@ extension Int16: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public static func fromResultObject(result: AnyObject) -> Int16? {
public static func fromResultObject(_ result: AnyObject) -> Int16? {
guard let value = (result as? NSNumber)?.longLongValue else {
guard let value = (result as? NSNumber)?.int64Value else {
return nil
}
@@ -475,12 +475,12 @@ extension Int32: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public static func fromResultObject(result: AnyObject) -> Int32? {
public static func fromResultObject(_ result: AnyObject) -> Int32? {
guard let value = (result as? NSNumber)?.longLongValue else {
guard let value = (result as? NSNumber)?.int64Value else {
return nil
}
@@ -495,12 +495,12 @@ extension Int64: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public static func fromResultObject(result: AnyObject) -> Int64? {
public static func fromResultObject(_ result: AnyObject) -> Int64? {
return (result as? NSNumber)?.longLongValue
return (result as? NSNumber)?.int64Value
}
}
@@ -511,12 +511,12 @@ extension Int: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public static func fromResultObject(result: AnyObject) -> Int? {
public static func fromResultObject(_ result: AnyObject) -> Int? {
guard let value = (result as? NSNumber)?.longLongValue else {
guard let value = (result as? NSNumber)?.int64Value else {
return nil
}
@@ -531,10 +531,10 @@ extension Double: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .DoubleAttributeType
return .doubleAttributeType
}
public static func fromResultObject(result: AnyObject) -> Double? {
public static func fromResultObject(_ result: AnyObject) -> Double? {
return (result as? NSNumber)?.doubleValue
}
@@ -547,10 +547,10 @@ extension Float: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .FloatAttributeType
return .floatAttributeType
}
public static func fromResultObject(result: AnyObject) -> Float? {
public static func fromResultObject(_ result: AnyObject) -> Float? {
return (result as? NSNumber)?.floatValue
}
@@ -563,12 +563,12 @@ extension String: SelectValueResultType {
public static var attributeType: NSAttributeType {
return .StringAttributeType
return .stringAttributeType
}
public static func fromResultObject(result: AnyObject) -> String? {
public static func fromResultObject(_ result: AnyObject) -> String? {
return result as? NSString as? String
return result as? String
}
}
@@ -579,12 +579,12 @@ extension NSNumber: SelectValueResultType {
public class var attributeType: NSAttributeType {
return .Integer64AttributeType
return .integer64AttributeType
}
public class func fromResultObject(result: AnyObject) -> Self? {
public class func fromResultObject(_ result: AnyObject) -> Self? {
func forceCast<T: NSNumber>(object: AnyObject) -> T? {
func forceCast<T: NSNumber>(_ object: AnyObject) -> T? {
return (object as? T)
}
@@ -599,12 +599,12 @@ extension NSString: SelectValueResultType {
public class var attributeType: NSAttributeType {
return .StringAttributeType
return .stringAttributeType
}
public class func fromResultObject(result: AnyObject) -> Self? {
public class func fromResultObject(_ result: AnyObject) -> Self? {
func forceCast<T: NSString>(object: AnyObject) -> T? {
func forceCast<T: NSString>(_ object: AnyObject) -> T? {
return (object as? T)
}
@@ -619,12 +619,12 @@ extension NSDecimalNumber {
public override class var attributeType: NSAttributeType {
return .DecimalAttributeType
return .decimalAttributeType
}
public override class func fromResultObject(result: AnyObject) -> Self? {
public override class func fromResultObject(_ result: AnyObject) -> Self? {
func forceCast<T: NSDecimalNumber>(object: AnyObject) -> T? {
func forceCast<T: NSDecimalNumber>(_ object: AnyObject) -> T? {
return (object as? T)
}
@@ -635,40 +635,32 @@ extension NSDecimalNumber {
// MARK: - NSDate: SelectValueResultType
extension NSDate: SelectValueResultType {
extension Date: SelectValueResultType {
public class var attributeType: NSAttributeType {
public static var attributeType: NSAttributeType {
return .DateAttributeType
return .dateAttributeType
}
public class func fromResultObject(result: AnyObject) -> Self? {
public static func fromResultObject(_ result: AnyObject) -> Date? {
func forceCast<T: NSDate>(object: AnyObject) -> T? {
return (object as? T)
}
return forceCast(result)
return result as? Date
}
}
// MARK: - NSData: SelectValueResultType
extension NSData: SelectValueResultType {
extension Data: SelectValueResultType {
public class var attributeType: NSAttributeType {
public static var attributeType: NSAttributeType {
return .BinaryDataAttributeType
return .binaryDataAttributeType
}
public class func fromResultObject(result: AnyObject) -> Self? {
public static func fromResultObject(_ result: AnyObject) -> Data? {
func forceCast<T: NSData>(object: AnyObject) -> T? {
return (object as? T)
}
return forceCast(result)
return result as? Data
}
}
@@ -679,12 +671,12 @@ extension NSManagedObjectID: SelectValueResultType {
public class var attributeType: NSAttributeType {
return .ObjectIDAttributeType
return .objectIDAttributeType
}
public class func fromResultObject(result: AnyObject) -> Self? {
public class func fromResultObject(_ result: AnyObject) -> Self? {
func forceCast<T: NSManagedObjectID>(object: AnyObject) -> T? {
func forceCast<T: NSManagedObjectID>(_ object: AnyObject) -> T? {
return (object as? T)
}
@@ -699,7 +691,7 @@ extension NSDictionary: SelectAttributesResultType {
// MARK: SelectAttributesResultType
public class func fromResultObjects(result: [AnyObject]) -> [[NSString: AnyObject]] {
public class func fromResultObjects(_ result: [AnyObject]) -> [[NSString: AnyObject]] {
return result as! [[NSString: AnyObject]]
}
@@ -708,12 +700,12 @@ extension NSDictionary: SelectAttributesResultType {
// MARK: - Internal
internal extension CollectionType where Generator.Element == SelectTerm {
internal extension Collection where Iterator.Element == SelectTerm {
internal func applyToFetchRequest<T>(fetchRequest: NSFetchRequest, owner: T) {
internal func applyToFetchRequest<T>(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>, owner: T) {
fetchRequest.includesPendingChanges = false
fetchRequest.resultType = .DictionaryResultType
fetchRequest.resultType = .dictionaryResultType
let entityDescription = fetchRequest.entity!
let propertiesByName = entityDescription.propertiesByName
@@ -724,7 +716,7 @@ internal extension CollectionType where Generator.Element == SelectTerm {
switch term {
case ._Attribute(let keyPath):
case ._attribute(let keyPath):
if let propertyDescription = propertiesByName[keyPath] {
propertiesToFetch.append(propertyDescription)
@@ -732,17 +724,17 @@ internal extension CollectionType where Generator.Element == SelectTerm {
else {
CoreStore.log(
.Warning,
.warning,
message: "The property \"\(keyPath)\" does not exist in entity \(cs_typeName(entityDescription.managedObjectClassName)) and will be ignored by \(cs_typeName(owner)) query clause."
)
}
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
case ._aggregate(let function, let keyPath, let alias, let nativeType):
if let attributeDescription = attributesByName[keyPath] {
let expressionDescription = NSExpressionDescription()
expressionDescription.name = alias
if nativeType == .UndefinedAttributeType {
if nativeType == .undefinedAttributeType {
expressionDescription.expressionResultType = attributeDescription.attributeType
}
@@ -760,17 +752,17 @@ internal extension CollectionType where Generator.Element == SelectTerm {
else {
CoreStore.log(
.Warning,
.warning,
message: "The attribute \"\(keyPath)\" does not exist in entity \(cs_typeName(entityDescription.managedObjectClassName)) and will be ignored by \(cs_typeName(owner)) query clause."
)
}
case ._Identity(let alias, let nativeType):
case ._identity(let alias, let nativeType):
let expressionDescription = NSExpressionDescription()
expressionDescription.name = alias
if nativeType == .UndefinedAttributeType {
if nativeType == .undefinedAttributeType {
expressionDescription.expressionResultType = .ObjectIDAttributeType
expressionDescription.expressionResultType = .objectIDAttributeType
}
else {
@@ -789,13 +781,13 @@ internal extension CollectionType where Generator.Element == SelectTerm {
switch self.first! {
case ._Attribute(let keyPath):
case ._attribute(let keyPath):
return keyPath
case ._Aggregate(_, _, let alias, _):
case ._aggregate(_, _, let alias, _):
return alias
case ._Identity(let alias, _):
case ._identity(let alias, _):
return alias
}
}
@@ -47,7 +47,7 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
/**
The block to customize the `NSFetchRequest`
*/
public let closure: (fetchRequest: NSFetchRequest) -> Void
public let closure: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void
/**
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.
- parameter closure: the block to customize the `NSFetchRequest`
*/
public init(_ closure: (fetchRequest: NSFetchRequest) -> Void) {
public init(_ closure: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) {
self.closure = closure
}
@@ -63,8 +63,8 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
// MARK: FetchClause, QueryClause, DeleteClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
self.closure(fetchRequest: fetchRequest)
self.closure(fetchRequest: unsafeBitCast(fetchRequest, to: NSFetchRequest<NSFetchRequestResult>.self))
}
}
@@ -29,17 +29,17 @@ import CoreData
public func &&(left: Where, right: Where) -> Where {
return Where(NSCompoundPredicate(type: .AndPredicateType, subpredicates: [left.predicate, right.predicate]))
return Where(CompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate]))
}
public func ||(left: Where, right: Where) -> Where {
return Where(NSCompoundPredicate(type: .OrPredicateType, subpredicates: [left.predicate, right.predicate]))
return Where(CompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate]))
}
public prefix func !(clause: Where) -> Where {
return Where(NSCompoundPredicate(type: .NotPredicateType, subpredicates: [clause.predicate]))
return Where(CompoundPredicate(type: .not, subpredicates: [clause.predicate]))
}
@@ -53,7 +53,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
/**
The `NSPredicate` for the fetch or query
*/
public let predicate: NSPredicate
public let predicate: Predicate
/**
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) {
self.init(NSPredicate(value: value))
self.init(Predicate(value: value))
}
/**
@@ -81,7 +81,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/
public init(_ format: String, _ args: NSObject...) {
self.init(NSPredicate(format: format, argumentArray: args))
self.init(Predicate(format: format, argumentArray: args))
}
/**
@@ -92,7 +92,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/
public init(_ format: String, argumentArray: [NSObject]?) {
self.init(NSPredicate(format: format, argumentArray: argumentArray))
self.init(Predicate(format: format, argumentArray: argumentArray))
}
/**
@@ -104,8 +104,8 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
public init(_ keyPath: KeyPath, isEqualTo value: NSObject?) {
self.init(value == nil
? NSPredicate(format: "\(keyPath) == nil")
: NSPredicate(format: "\(keyPath) == %@", argumentArray: [value!]))
? Predicate(format: "\(keyPath) == nil")
: Predicate(format: "\(keyPath) == %@", argumentArray: [value!]))
}
/**
@@ -116,7 +116,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
*/
public init(_ keyPath: KeyPath, isMemberOf list: [NSObject]) {
self.init(NSPredicate(format: "\(keyPath) IN %@", list))
self.init(Predicate(format: "\(keyPath) IN %@", list))
}
/**
@@ -125,9 +125,9 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
- parameter keyPath: the keyPath to compare with
- parameter list: the sequence to check membership of
*/
public init<S: SequenceType where S.Generator.Element: NSObject>(_ keyPath: KeyPath, isMemberOf list: S) {
public init<S: Sequence where S.Iterator.Element: NSObject>(_ keyPath: KeyPath, isMemberOf list: S) {
self.init(NSPredicate(format: "\(keyPath) IN %@", Array(list) as NSArray))
self.init(Predicate(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
*/
public init(_ predicate: NSPredicate) {
public init(_ predicate: Predicate) {
self.predicate = predicate
}
@@ -143,13 +143,13 @@ public struct Where: FetchClause, QueryClause, DeleteClause, Hashable {
// MARK: FetchClause, QueryClause, DeleteClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
if let predicate = fetchRequest.predicate where predicate != self.predicate {
CoreStore.log(
.Warning,
message: "An existing predicate for the \(cs_typeName(NSFetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
.warning,
message: "An existing predicate for the \(cs_typeName(fetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
)
}
@@ -38,7 +38,7 @@ public extension CoreStore {
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
@warn_unused_result
public static func fetchExisting<T: NSManagedObject>(object: T) -> T? {
public static func fetchExisting<T: NSManagedObject>(_ object: T) -> T? {
return self.defaultStack.fetchExisting(object)
}
@@ -50,7 +50,7 @@ public extension CoreStore {
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
@warn_unused_result
public static func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
public static func fetchExisting<T: NSManagedObject>(_ objectID: NSManagedObjectID) -> T? {
return self.defaultStack.fetchExisting(objectID)
}
@@ -62,7 +62,7 @@ public extension CoreStore {
- returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/
@warn_unused_result
public static func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
public static func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] {
return self.defaultStack.fetchExisting(objects)
}
@@ -74,7 +74,7 @@ public extension CoreStore {
- returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/
@warn_unused_result
public static func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
public static func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] {
return self.defaultStack.fetchExisting(objectIDs)
}
@@ -87,7 +87,7 @@ public extension CoreStore {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> T? {
public static func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> T? {
return self.defaultStack.fetchOne(from, fetchClauses)
}
@@ -100,7 +100,7 @@ public extension CoreStore {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
public static func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
return self.defaultStack.fetchOne(from, fetchClauses)
}
@@ -113,7 +113,7 @@ public extension CoreStore {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
public static func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
return self.defaultStack.fetchAll(from, fetchClauses)
}
@@ -126,7 +126,7 @@ public extension CoreStore {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
public static func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
return self.defaultStack.fetchAll(from, fetchClauses)
}
@@ -139,7 +139,7 @@ public extension CoreStore {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
public static func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
return self.defaultStack.fetchCount(from, fetchClauses)
}
@@ -152,7 +152,7 @@ public extension CoreStore {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
public static func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
return self.defaultStack.fetchCount(from, fetchClauses)
}
@@ -165,7 +165,7 @@ public extension CoreStore {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
public static func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
return self.defaultStack.fetchObjectID(from, fetchClauses)
}
@@ -178,7 +178,7 @@ public extension CoreStore {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
public static func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
return self.defaultStack.fetchObjectID(from, fetchClauses)
}
@@ -191,7 +191,7 @@ public extension CoreStore {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
public static func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
return self.defaultStack.fetchObjectIDs(from, fetchClauses)
}
@@ -204,7 +204,7 @@ public extension CoreStore {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public static func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
public static func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
return self.defaultStack.fetchObjectIDs(from, fetchClauses)
}
@@ -220,7 +220,7 @@ public extension CoreStore {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public static func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
public static func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
return self.defaultStack.queryValue(from, selectClause, queryClauses)
}
@@ -236,7 +236,7 @@ public extension CoreStore {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public static func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
public static func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
return self.defaultStack.queryValue(from, selectClause, queryClauses)
}
@@ -252,7 +252,7 @@ public extension CoreStore {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public static func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
public static func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
return self.defaultStack.queryAttributes(from, selectClause, queryClauses)
}
@@ -268,7 +268,7 @@ public extension CoreStore {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public static func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
public static func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
return self.defaultStack.queryAttributes(from, selectClause, queryClauses)
}
@@ -41,11 +41,11 @@ public extension DataStack {
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject>(object: T) -> T? {
public func fetchExisting<T: NSManagedObject>(_ object: T) -> T? {
do {
return (try self.mainContext.existingObjectWithID(object.objectID) as! T)
return (try self.mainContext.existingObject(with: object.objectID) as! T)
}
catch _ {
@@ -60,11 +60,11 @@ public extension DataStack {
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
public func fetchExisting<T: NSManagedObject>(_ objectID: NSManagedObjectID) -> T? {
do {
return (try self.mainContext.existingObjectWithID(objectID) as! T)
return (try self.mainContext.existingObject(with: objectID) as! T)
}
catch _ {
@@ -79,9 +79,9 @@ public extension DataStack {
- returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == T>(_ objects: S) -> [T] {
return objects.flatMap { (try? self.mainContext.existingObjectWithID($0.objectID)) as? T }
return objects.flatMap { (try? self.mainContext.existingObject(with: $0.objectID)) as? T }
}
/**
@@ -91,9 +91,9 @@ public extension DataStack {
- returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/
@warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
public func fetchExisting<T: NSManagedObject, S: Sequence where S.Iterator.Element == NSManagedObjectID>(_ objectIDs: S) -> [T] {
return objectIDs.flatMap { (try? self.mainContext.existingObjectWithID($0)) as? T }
return objectIDs.flatMap { (try? self.mainContext.existingObject(with: $0)) as? T }
}
/**
@@ -104,10 +104,10 @@ public extension DataStack {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> T? {
public func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> T? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchOne(from, fetchClauses)
@@ -121,10 +121,10 @@ public extension DataStack {
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
public func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchOne(from, fetchClauses)
@@ -138,10 +138,10 @@ public extension DataStack {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
public func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchAll(from, fetchClauses)
@@ -155,10 +155,10 @@ public extension DataStack {
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
public func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchAll(from, fetchClauses)
@@ -172,10 +172,10 @@ public extension DataStack {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
public func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchCount(from, fetchClauses)
@@ -189,10 +189,10 @@ public extension DataStack {
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
public func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchCount(from, fetchClauses)
@@ -206,10 +206,10 @@ public extension DataStack {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
public func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchObjectID(from, fetchClauses)
@@ -223,10 +223,10 @@ public extension DataStack {
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
public func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchObjectID(from, fetchClauses)
@@ -240,10 +240,10 @@ public extension DataStack {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
public func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchObjectIDs(from, fetchClauses)
@@ -257,10 +257,10 @@ public extension DataStack {
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/
@warn_unused_result
public func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
public func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.fetchObjectIDs(from, fetchClauses)
@@ -277,10 +277,10 @@ public extension DataStack {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.queryValue(from, selectClause, queryClauses)
@@ -297,10 +297,10 @@ public extension DataStack {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
public func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.queryValue(from, selectClause, queryClauses)
@@ -317,10 +317,10 @@ public extension DataStack {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
public func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.queryAttributes(from, selectClause, queryClauses)
@@ -337,10 +337,10 @@ public extension DataStack {
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
*/
@warn_unused_result
public func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
public func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.mainContext.queryAttributes(from, selectClause, queryClauses)
@@ -34,7 +34,7 @@ import CoreData
*/
public protocol FetchClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest<T: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<T>)
}
@@ -45,7 +45,7 @@ public protocol FetchClause {
*/
public protocol QueryClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest<T: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<T>)
}
@@ -56,5 +56,5 @@ public protocol QueryClause {
*/
public protocol DeleteClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest<T: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<T>)
}
@@ -40,7 +40,7 @@ public extension BaseDataTransaction {
- returns: the created `ImportableObject` instance, or `nil` if the import was ignored
*/
public func importObject<T where T: NSManagedObject, T: ImportableObject>(
into: Into<T>,
_ into: Into<T>,
source: T.ImportSource) throws -> T? {
CoreStore.assert(
@@ -69,7 +69,7 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableObject` methods
*/
public func importObject<T where T: NSManagedObject, T: ImportableObject>(
object: T,
_ object: T,
source: T.ImportSource) throws {
CoreStore.assert(
@@ -96,8 +96,8 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableObject` methods
- returns: the array of created `ImportableObject` instances
*/
public func importObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableObject, S.Generator.Element == T.ImportSource>(
into: Into<T>,
public func importObjects<T, S: Sequence where T: NSManagedObject, T: ImportableObject, S.Iterator.Element == T.ImportSource>(
_ into: Into<T>,
sourceArray: S) throws -> [T] {
CoreStore.assert(
@@ -133,7 +133,7 @@ public extension BaseDataTransaction {
- returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored
*/
public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>(
into: Into<T>,
_ into: Into<T>,
source: T.ImportSource) throws -> T? {
CoreStore.assert(
@@ -184,8 +184,8 @@ public extension BaseDataTransaction {
- throws: an `ErrorType` thrown from any of the `ImportableUniqueObject` methods
- returns: the array of created/updated `ImportableUniqueObject` instances
*/
public func importUniqueObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableUniqueObject, S.Generator.Element == T.ImportSource>(
into: Into<T>,
public func importUniqueObjects<T, S: Sequence where T: NSManagedObject, T: ImportableUniqueObject, S.Iterator.Element == T.ImportSource>(
_ into: Into<T>,
sourceArray: S,
@noescape preProcess: (mapping: [T.UniqueIDType: T.ImportSource]) throws -> [T.UniqueIDType: T.ImportSource] = { $0 }) throws -> [T] {
@@ -220,7 +220,7 @@ public extension BaseDataTransaction {
let uniqueIDValue = object.uniqueIDValue
guard let source = mapping.removeValueForKey(uniqueIDValue)
guard let source = mapping.removeValue(forKey: uniqueIDValue)
where T.shouldUpdateFromImportSource(source, inTransaction: self) else {
return
+3 -3
View File
@@ -62,7 +62,7 @@ public protocol ImportableObject: class {
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
- returns: `true` if an object should be created from `source`. Return `false` to ignore.
*/
static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
static func shouldInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
/**
Implements the actual importing of data from `source`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importObjects(:sourceArray:)` call to be cancelled.
@@ -70,7 +70,7 @@ public protocol ImportableObject: class {
- parameter source: the object to import from
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
*/
func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
func didInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
}
@@ -78,7 +78,7 @@ public protocol ImportableObject: class {
public extension ImportableObject {
static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
static func shouldInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
return true
}
@@ -78,7 +78,7 @@ public protocol ImportableUniqueObject: ImportableObject {
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
- returns: `true` if an object should be created from `source`. Return `false` to ignore.
*/
static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
static func shouldInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
/**
Return `true` if an object should be updated from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`.
@@ -87,7 +87,7 @@ public protocol ImportableUniqueObject: ImportableObject {
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
- returns: `true` if an object should be updated from `source`. Return `false` to ignore.
*/
static func shouldUpdateFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
static func shouldUpdateFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool
/**
Return the unique ID as extracted from `source`. This method is called before `shouldInsertFromImportSource(...)` or `shouldUpdateFromImportSource(...)`. Return `nil` to skip importing from `source`. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled.
@@ -96,7 +96,7 @@ public protocol ImportableUniqueObject: ImportableObject {
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
- returns: the unique ID as extracted from `source`, or `nil` to skip importing from `source`.
*/
static func uniqueIDFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws -> UniqueIDType?
static func uniqueIDFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) throws -> UniqueIDType?
/**
Implements the actual importing of data from `source`. This method is called just after the object is created and assigned its unique ID as returned from `uniqueIDFromImportSource(...)`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled. The default implementation simply calls `updateFromImportSource(...)`.
@@ -104,7 +104,7 @@ public protocol ImportableUniqueObject: ImportableObject {
- parameter source: the object to import from
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
*/
func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
func didInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
/**
Implements the actual importing of data from `source`. This method is called just after the existing object is fetched using its unique ID. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled.
@@ -112,7 +112,7 @@ public protocol ImportableUniqueObject: ImportableObject {
- parameter source: the object to import from
- parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed.
*/
func updateFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
func updateFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) throws
}
@@ -120,17 +120,17 @@ public protocol ImportableUniqueObject: ImportableObject {
public extension ImportableUniqueObject {
static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
static func shouldInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
return self.shouldUpdateFromImportSource(source, inTransaction: transaction)
}
static func shouldUpdateFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
static func shouldUpdateFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool {
return true
}
func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws {
func didInsertFromImportSource(_ source: ImportSource, inTransaction transaction: BaseDataTransaction) throws {
try self.updateFromImportSource(source, inTransaction: transaction)
}
+12 -1
View File
@@ -31,7 +31,18 @@ import CoreData
// Bugfix for NSFetchRequest messing up memory management for `affectedStores`
// http://stackoverflow.com/questions/14396375/nsfetchedresultscontroller-crashes-in-ios-6-if-affectedstores-is-specified
internal final class CoreStoreFetchRequest: NSFetchRequest {
internal final class CoreStoreFetchRequest<T: NSFetchRequestResult>: NSFetchRequest<NSFetchRequestResult> {
// MARK: Internal
@nonobjc
internal func dynamicCast<U: NSFetchRequestResult>() -> NSFetchRequest<U> {
return unsafeBitCast(self, to: NSFetchRequest<U>.self)
}
// MARK: NSFetchRequest
@objc
override var affectedStores: [NSPersistentStore]? {
@@ -31,12 +31,12 @@ import CoreData
// MARK: - CoreStoreFetchedResultsController
internal final class CoreStoreFetchedResultsController: NSFetchedResultsController {
internal final class CoreStoreFetchedResultsController: NSFetchedResultsController<NSManagedObject> {
// MARK: Internal
@nonobjc
internal convenience init<T: NSManagedObject>(dataStack: DataStack, fetchRequest: NSFetchRequest, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (fetchRequest: NSFetchRequest) -> 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(
context: dataStack.mainContext,
@@ -48,14 +48,14 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
}
@nonobjc
internal init<T: NSManagedObject>(context: NSManagedObjectContext, fetchRequest: NSFetchRequest, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) {
internal init<T: NSManagedObject>(context: NSManagedObjectContext, fetchRequest: NSFetchRequest<NSManagedObject>, from: From<T>? = nil, sectionBy: SectionBy? = nil, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
_ = from?.applyToFetchRequest(
fetchRequest,
context: context,
applyAffectedStores: false
)
applyFetchClauses(fetchRequest: fetchRequest)
applyFetchClauses(fetchRequest: fetchRequest.cs_dynamicCast())
if let from = from {
@@ -68,7 +68,7 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
guard let from = (fetchRequest.entity.flatMap { $0.managedObjectClassName }).flatMap(NSClassFromString).flatMap(From.init) else {
CoreStore.abort("Attempted to create an \(cs_typeName(NSFetchedResultsController)) without a \(cs_typeName(From)) clause or an \(cs_typeName(NSEntityDescription)).")
CoreStore.abort("Attempted to create a \(CoreStoreFetchedResultsController.self) without a \(cs_typeName(From<T>.self)) clause or an \(cs_typeName(NSEntityDescription.self)).")
}
self.reapplyAffectedStores = { fetchRequest, context in
@@ -91,13 +91,19 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
if !self.reapplyAffectedStores(fetchRequest: self.fetchRequest, context: self.managedObjectContext) {
CoreStore.log(
.Warning,
message: "Attempted to perform a fetch on an \(cs_typeName(NSFetchedResultsController)) but could not find any persistent store for the entity \(cs_typeName(self.fetchRequest.entityName))"
.warning,
message: "Attempted to perform a fetch on an \(cs_typeName(self)) but could not find any persistent store for the entity \(cs_typeName(self.fetchRequest.entityName))"
)
}
try self.performFetch()
}
@nonobjc
internal func dynamicCast<U: NSFetchRequestResult>() -> NSFetchedResultsController<U> {
return unsafeBitCast(self, to: NSFetchedResultsController<U>.self)
}
deinit {
self.delegate = nil
@@ -107,7 +113,7 @@ internal final class CoreStoreFetchedResultsController: NSFetchedResultsControll
// MARK: Private
@nonobjc
private let reapplyAffectedStores: (fetchRequest: NSFetchRequest, context: NSManagedObjectContext) -> Bool
private let reapplyAffectedStores: (fetchRequest: NSFetchRequest<NSManagedObject>, context: NSManagedObjectContext) -> Bool
}
#endif
@@ -33,21 +33,21 @@ import CoreData
internal protocol FetchedResultsControllerHandler: class {
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeObject anObject: AnyObject, atIndexPath indexPath: IndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType)
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType)
func controllerWillChangeContent(controller: NSFetchedResultsController)
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
func controllerDidChangeContent(controller: NSFetchedResultsController)
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String?
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, sectionIndexTitleForSectionName sectionName: String?) -> String?
}
// MARK: - FetchedResultsControllerDelegate
internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate {
internal final class FetchedResultsControllerDelegate<EntityType: NSManagedObject>: NSObject, NSFetchedResultsControllerDelegate {
// MARK: Internal
@@ -58,7 +58,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
internal weak var handler: FetchedResultsControllerHandler?
@nonobjc
internal weak var fetchedResultsController: NSFetchedResultsController? {
internal weak var fetchedResultsController: CoreStoreFetchedResultsController? {
didSet {
@@ -76,7 +76,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
// MARK: NSFetchedResultsControllerDelegate
@objc
dynamic func controllerWillChangeContent(controller: NSFetchedResultsController) {
dynamic func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard self.enabled else {
@@ -90,7 +90,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
}
@objc
dynamic func controllerDidChangeContent(controller: NSFetchedResultsController) {
dynamic func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard self.enabled else {
@@ -101,7 +101,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
}
@objc
dynamic func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
dynamic func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: AnyObject, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
guard self.enabled else {
@@ -123,8 +123,8 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
switch actualType {
case .Update:
guard let section = indexPath?.indexAtPosition(0) else {
case .update:
guard let section = indexPath?[0] else {
return
}
@@ -134,7 +134,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
return
}
case .Move:
case .move:
guard let indexPath = indexPath, let newIndexPath = newIndexPath else {
return
@@ -143,25 +143,25 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
break
}
if self.insertedSections.contains(indexPath.indexAtPosition(0)) {
if self.insertedSections.contains(indexPath[0]) {
// Observers that handle the .Move change are advised to delete then reinsert the object instead of just moving. This is especially true when indexPath and newIndexPath are equal. For example, calling tableView.moveRowAtIndexPath(_:toIndexPath) when both indexPaths are the same will crash the tableView.
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: indexPath,
forChangeType: .Move,
forChangeType: .move,
newIndexPath: newIndexPath
)
return
}
if self.deletedSections.contains(indexPath.indexAtPosition(0)) {
if self.deletedSections.contains(indexPath[0]) {
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: nil,
forChangeType: .Insert,
forChangeType: .insert,
newIndexPath: indexPath
)
return
@@ -170,7 +170,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
controller,
didChangeObject: anObject,
atIndexPath: indexPath,
forChangeType: .Update,
forChangeType: .update,
newIndexPath: nil
)
return
@@ -189,7 +189,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
}
@objc
dynamic func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
dynamic func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
guard self.enabled else {
@@ -198,8 +198,8 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
switch type {
case .Delete: self.deletedSections.insert(sectionIndex)
case .Insert: self.insertedSections.insert(sectionIndex)
case .delete: self.deletedSections.insert(sectionIndex)
case .insert: self.insertedSections.insert(sectionIndex)
default: break
}
@@ -212,7 +212,7 @@ internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResult
}
@objc
dynamic func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String) -> String? {
dynamic func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, sectionIndexTitleForSectionName sectionName: String) -> String? {
return self.handler?.controller(
controller,
+14 -14
View File
@@ -28,12 +28,12 @@ import Foundation
// MARK: - Custom AutoreleasePool
internal func cs_autoreleasepool(@noescape closure: () -> Void) {
internal func cs_autoreleasepool(@noescape _ closure: () -> Void) {
autoreleasepool(closure)
}
internal func cs_autoreleasepool<T>(@noescape closure: () -> T) -> T {
internal func cs_autoreleasepool<T>(@noescape _ closure: () -> T) -> T {
var closureValue: T!
autoreleasepool {
@@ -44,10 +44,10 @@ internal func cs_autoreleasepool<T>(@noescape closure: () -> T) -> T {
return closureValue
}
internal func cs_autoreleasepool<T>(@noescape closure: () throws -> T) throws -> T {
internal func cs_autoreleasepool<T>(@noescape _ closure: () throws -> T) throws -> T {
var closureValue: T!
var closureError: ErrorType?
var closureError: ErrorProtocol?
autoreleasepool {
do {
@@ -67,9 +67,9 @@ internal func cs_autoreleasepool<T>(@noescape closure: () throws -> T) throws ->
return closureValue
}
internal func cs_autoreleasepool(@noescape closure: () throws -> Void) throws {
internal func cs_autoreleasepool(@noescape _ closure: () throws -> Void) throws {
var closureError: ErrorType?
var closureError: ErrorProtocol?
autoreleasepool {
do {
@@ -88,7 +88,7 @@ internal func cs_autoreleasepool(@noescape closure: () throws -> Void) throws {
}
}
internal func cs_getAssociatedObjectForKey<T: AnyObject>(key: UnsafePointer<Void>, inObject object: AnyObject) -> T? {
internal func cs_getAssociatedObjectForKey<T: AnyObject>(_ key: UnsafePointer<Void>, inObject object: AnyObject) -> T? {
switch objc_getAssociatedObject(object, key) {
@@ -103,17 +103,17 @@ internal func cs_getAssociatedObjectForKey<T: AnyObject>(key: UnsafePointer<Void
}
}
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: UnsafePointer<Void>, inObject object: AnyObject) {
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: UnsafePointer<Void>, inObject object: AnyObject) {
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: UnsafePointer<Void>, inObject object: AnyObject) {
if let associatedObject = associatedObject {
@@ -128,22 +128,22 @@ internal func cs_setAssociatedWeakObject<T: AnyObject>(associatedObject: T?, for
// MARK: Printing Utilities
internal func cs_typeName<T>(value: T) -> String {
internal func cs_typeName<T>(_ value: T) -> String {
return "'\(String(reflecting: value.dynamicType))'"
}
internal func cs_typeName<T>(value: T.Type) -> String {
internal func cs_typeName<T>(_ value: T.Type) -> String {
return "'\(value)'"
}
internal func cs_typeName(value: AnyClass) -> String {
internal func cs_typeName(_ value: AnyClass) -> String {
return "'\(value)'"
}
internal func cs_typeName(name: String?) -> String {
internal func cs_typeName(_ name: String?) -> String {
return "<\(name ?? "unknown")>"
}
+5 -5
View File
@@ -29,13 +29,13 @@ import CoreData
// MARK: - MigrationManager
internal final class MigrationManager: NSMigrationManager, NSProgressReporting {
internal final class MigrationManager: NSMigrationManager, ProgressReporting {
// MARK: NSObject
override func didChangeValueForKey(key: String) {
override func didChangeValue(forKey key: String) {
super.didChangeValueForKey(key)
super.didChangeValue(forKey: key)
guard key == "migrationProgress" else {
@@ -48,7 +48,7 @@ internal final class MigrationManager: NSMigrationManager, NSProgressReporting {
// MARK: NSMigrationManager
init(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, progress: NSProgress) {
init(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, progress: Progress) {
self.progress = progress
@@ -58,5 +58,5 @@ internal final class MigrationManager: NSMigrationManager, NSProgressReporting {
// MARK: NSProgressReporting
let progress: NSProgress
let progress: Progress
}
@@ -0,0 +1,20 @@
//
// NSFetchRequest+CoreStore.swift
// CoreStore
//
// Created by John Rommel Estropia on 2016/07/20.
// Copyright © 2016 John Rommel Estropia. All rights reserved.
//
import CoreData
internal extension NSFetchRequest {
// MARK: Internal
@nonobjc
internal func cs_dynamicCast<U: NSFetchRequestResult>() -> NSFetchRequest<U> {
return unsafeBitCast(self, to: NSFetchRequest<U>.self)
}
}
@@ -50,7 +50,7 @@ internal extension NSManagedObjectContext {
set {
cs_setAssociatedCopiedObject(
NSNumber(bool: newValue),
NSNumber(value: newValue),
forKey: &PropertyKeys.shouldCascadeSavesToParent,
inObject: self
)
@@ -58,26 +58,26 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func entityDescriptionForEntityType(entity: NSManagedObject.Type) -> NSEntityDescription? {
internal func entityDescriptionForEntityType(_ entity: NSManagedObject.Type) -> NSEntityDescription? {
return self.entityDescriptionForEntityClass(entity)
}
@nonobjc
internal func entityDescriptionForEntityClass(entity: AnyClass) -> NSEntityDescription? {
internal func entityDescriptionForEntityClass(_ entity: AnyClass) -> NSEntityDescription? {
guard let entityName = self.parentStack?.entityNameForEntityClass(entity) else {
return nil
}
return NSEntityDescription.entityForName(
entityName,
inManagedObjectContext: self
return NSEntityDescription.entity(
forEntityName: entityName,
in: self
)
}
@nonobjc
internal func setupForCoreStoreWithContextName(contextName: String) {
internal func setupForCoreStoreWithContextName(_ contextName: String) {
#if USE_FRAMEWORKS
@@ -91,7 +91,7 @@ internal extension NSManagedObjectContext {
#endif
self.observerForWillSaveNotification = NotificationObserver(
notificationName: NSManagedObjectContextWillSaveNotification,
notificationName: NSNotification.Name.NSManagedObjectContextWillSave.rawValue,
object: self,
closure: { (note) -> Void in
@@ -105,7 +105,7 @@ internal extension NSManagedObjectContext {
do {
try context.obtainPermanentIDsForObjects(Array(insertedObjects))
try context.obtainPermanentIDs(for: Array(insertedObjects))
}
catch {
@@ -34,15 +34,15 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Fetch Existing
@nonobjc
internal func fetchExisting<T: NSManagedObject>(object: T) -> T? {
internal func fetchExisting<T: NSManagedObject>(_ object: T) -> T? {
if object.objectID.temporaryID {
if object.objectID.isTemporaryID {
do {
try withExtendedLifetime(self) { (context: NSManagedObjectContext) -> Void in
try context.obtainPermanentIDsForObjects([object])
try context.obtainPermanentIDs(for: [object])
}
}
catch {
@@ -54,10 +54,9 @@ internal extension NSManagedObjectContext {
return nil
}
}
do {
let existingObject = try self.existingObjectWithID(object.objectID)
let existingObject = try self.existingObject(with: object.objectID)
return (existingObject as! T)
}
catch {
@@ -74,38 +73,38 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Fetch One
@nonobjc
internal func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> T? {
internal func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> T? {
return self.fetchOne(from, fetchClauses)
}
@nonobjc
internal func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
internal func fetchOne<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchOne(fetchRequest)
return self.fetchOne(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchOne<T: NSManagedObject>(fetchRequest: NSFetchRequest) -> T? {
internal func fetchOne<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> T? {
var fetchResults: [T]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [T]
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -120,7 +119,6 @@ internal extension NSManagedObjectContext {
)
return nil
}
return fetchResults?.first
}
@@ -128,38 +126,38 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Fetch All
@nonobjc
internal func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
internal func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
return self.fetchAll(from, fetchClauses)
}
@nonobjc
internal func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
internal func fetchAll<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchAll(fetchRequest)
return self.fetchAll(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchAll<T: NSManagedObject>(fetchRequest: NSFetchRequest) -> [T]? {
internal func fetchAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> [T]? {
var fetchResults: [T]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [T]
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -174,7 +172,6 @@ internal extension NSManagedObjectContext {
)
return nil
}
return fetchResults
}
@@ -182,15 +179,15 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Count
@nonobjc
internal func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
internal func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
return self.fetchCount(from, fetchClauses)
}
@nonobjc
internal func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
internal func fetchCount<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
@@ -198,27 +195,33 @@ internal extension NSManagedObjectContext {
return nil
}
return self.fetchCount(fetchRequest)
return self.fetchCount(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchCount(fetchRequest: NSFetchRequest) -> Int? {
internal func fetchCount<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> Int? {
var count = 0
var error: NSError?
self.performBlockAndWait {
var countError: ErrorProtocol?
self.performAndWait {
count = self.countForFetchRequest(fetchRequest, error: &error)
do {
count = try self.count(for: fetchRequest)
}
catch {
countError = error
}
}
if count == NSNotFound {
CoreStore.log(
CoreStoreError(error),
"Failed executing fetch request."
CoreStoreError(countError),
"Failed executing count request."
)
return nil
}
return count
}
@@ -226,38 +229,38 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Object ID
@nonobjc
internal func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
internal func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
return self.fetchObjectID(from, fetchClauses)
}
@nonobjc
internal func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
internal func fetchObjectID<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObjectID>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectIDResultType
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchObjectID(fetchRequest)
return self.fetchObjectID(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchObjectID(fetchRequest: NSFetchRequest) -> NSManagedObjectID? {
internal func fetchObjectID(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> NSManagedObjectID? {
var fetchResults: [NSManagedObjectID]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [NSManagedObjectID]
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -272,7 +275,6 @@ internal extension NSManagedObjectContext {
)
return nil
}
return fetchResults?.first
}
@@ -280,38 +282,38 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Object IDs
@nonobjc
internal func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
internal func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
return self.fetchObjectIDs(from, fetchClauses)
}
@nonobjc
internal func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
internal func fetchObjectIDs<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObjectID>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectIDResultType
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchObjectIDs(fetchRequest)
return self.fetchObjectIDs(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchObjectIDs(fetchRequest: NSFetchRequest) -> [NSManagedObjectID]? {
internal func fetchObjectIDs(_ fetchRequest: NSFetchRequest<NSManagedObjectID>) -> [NSManagedObjectID]? {
var fetchResults: [NSManagedObjectID]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [NSManagedObjectID]
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -326,7 +328,6 @@ internal extension NSManagedObjectContext {
)
return nil
}
return fetchResults
}
@@ -334,19 +335,19 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Delete All
@nonobjc
internal func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: DeleteClause...) -> Int? {
internal func deleteAll<T: NSManagedObject>(_ from: From<T>, _ deleteClauses: DeleteClause...) -> Int? {
return self.deleteAll(from, deleteClauses)
}
@nonobjc
internal func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: [DeleteClause]) -> Int? {
internal func deleteAll<T: NSManagedObject>(_ from: From<T>, _ deleteClauses: [DeleteClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchRequest.returnsObjectsAsFaults = true
fetchRequest.includesPropertyValues = false
deleteClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
@@ -355,24 +356,24 @@ internal extension NSManagedObjectContext {
return nil
}
return self.deleteAll(fetchRequest)
return self.deleteAll(fetchRequest.dynamicCast())
}
@nonobjc
internal func deleteAll(fetchRequest: NSFetchRequest) -> Int? {
internal func deleteAll<T: NSManagedObject>(_ fetchRequest: NSFetchRequest<T>) -> Int? {
var numberOfDeletedObjects: Int?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
cs_autoreleasepool {
do {
let fetchResults = try self.executeFetchRequest(fetchRequest) as? [NSManagedObject] ?? []
let fetchResults = try self.fetch(fetchRequest)
for object in fetchResults {
self.deleteObject(object)
self.delete(object)
}
numberOfDeletedObjects = fetchResults.count
}
@@ -390,7 +391,6 @@ internal extension NSManagedObjectContext {
)
return nil
}
return numberOfDeletedObjects
}
@@ -398,15 +398,15 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Value
@nonobjc
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
return self.queryValue(from, selectClause, queryClauses)
}
@nonobjc
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(_ from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSFetchRequestResult>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
@@ -423,15 +423,15 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func queryValue<U: SelectValueResultType>(selectTerms: [SelectTerm], fetchRequest: NSFetchRequest) -> U? {
internal func queryValue<U: SelectValueResultType>(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> U? {
var fetchResults: [AnyObject]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest)
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -456,15 +456,15 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func queryValue(selectTerms: [SelectTerm], fetchRequest: NSFetchRequest) -> AnyObject? {
internal func queryValue(_ selectTerms: [SelectTerm], fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> AnyObject? {
var fetchResults: [AnyObject]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest)
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -492,15 +492,15 @@ internal extension NSManagedObjectContext {
// MARK: Internal: Attributes
@nonobjc
internal func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
internal func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
return self.queryAttributes(from, selectClause, queryClauses)
}
@nonobjc
internal func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
internal func queryAttributes<T: NSManagedObject>(_ from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSFetchRequestResult>()
let storeFound = from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
@@ -516,15 +516,15 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func queryAttributes(fetchRequest: NSFetchRequest) -> [[NSString: AnyObject]]? {
internal func queryAttributes(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> [[NSString: AnyObject]]? {
var fetchResults: [AnyObject]?
var fetchError: ErrorType?
self.performBlockAndWait {
var fetchError: ErrorProtocol?
self.performAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest)
fetchResults = try self.fetch(fetchRequest)
}
catch {
@@ -38,7 +38,7 @@ internal extension NSManagedObjectContext {
get {
if let parentContext = self.parentContext {
if let parentContext = self.parent {
return parentContext.parentStack
}
@@ -47,7 +47,7 @@ internal extension NSManagedObjectContext {
}
set {
guard self.parentContext == nil else {
guard self.parent == nil else {
return
}
@@ -61,9 +61,9 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal static func rootSavingContextForCoordinator(coordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext {
internal static func rootSavingContextForCoordinator(_ coordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
context.undoManager = nil
@@ -72,18 +72,18 @@ internal extension NSManagedObjectContext {
#if os(iOS) || os(OSX)
context.observerForDidImportUbiquitousContentChangesNotification = NotificationObserver(
notificationName: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
notificationName: NSNotification.Name.NSPersistentStoreDidImportUbiquitousContentChanges.rawValue,
object: coordinator,
closure: { [weak context] (note) -> Void in
context?.performBlock { () -> Void in
context?.perform { () -> Void in
let updatedObjectIDs = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObjectID>) ?? []
let updatedObjectIDs = ((note as NSNotification).userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObjectID>) ?? []
for objectID in updatedObjectIDs {
context?.objectWithID(objectID).willAccessValueForKey(nil)
context?.object(with: objectID).willAccessValue(forKey: nil)
}
context?.mergeChangesFromContextDidSaveNotification(note)
context?.mergeChanges(fromContextDidSave: note)
}
}
)
@@ -94,15 +94,15 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal static func mainContextForRootContext(rootContext: NSManagedObjectContext) -> NSManagedObjectContext {
internal static func mainContextForRootContext(_ rootContext: NSManagedObjectContext) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.parentContext = rootContext
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = rootContext
context.mergePolicy = NSRollbackMergePolicy
context.undoManager = nil
context.setupForCoreStoreWithContextName("com.corestore.maincontext")
context.observerForDidSaveNotification = NotificationObserver(
notificationName: NSManagedObjectContextDidSaveNotification,
notificationName: NSNotification.Name.NSManagedObjectContextDidSave.rawValue,
object: rootContext,
closure: { [weak context] (note) -> Void in
@@ -113,21 +113,21 @@ internal extension NSManagedObjectContext {
}
let mergeChanges = { () -> Void in
let updatedObjects = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? []
let updatedObjects = ((note as NSNotification).userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? []
for object in updatedObjects {
context.objectWithID(object.objectID).willAccessValueForKey(nil)
context.object(with: object.objectID).willAccessValue(forKey: nil)
}
context.mergeChangesFromContextDidSaveNotification(note)
context.mergeChanges(fromContextDidSave: note)
}
if rootContext.isSavingSynchronously == true {
context.performBlockAndWait(mergeChanges)
context.performAndWait(mergeChanges)
}
else {
context.performBlock(mergeChanges)
context.perform(mergeChanges)
}
}
)
@@ -70,7 +70,7 @@ internal extension NSManagedObjectContext {
set {
cs_setAssociatedWeakObject(
newValue.flatMap { NSNumber(bool: $0) },
newValue.flatMap { NSNumber(value: $0) },
forKey: &PropertyKeys.isSavingSynchronously,
inObject: self
)
@@ -88,10 +88,10 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func temporaryContextInTransactionWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext {
internal func temporaryContextInTransactionWithConcurrencyType(_ concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: concurrencyType)
context.parentContext = self
context.parent = self
context.parentStack = self.parentStack
context.setupForCoreStoreWithContextName("com.corestore.temporarycontext")
context.shouldCascadeSavesToParent = (self.parentStack?.rootSavingContext == self)
@@ -105,7 +105,7 @@ internal extension NSManagedObjectContext {
var result = SaveResult(hasChanges: false)
self.performBlockAndWait {
self.performAndWait {
guard self.hasChanges else {
@@ -123,20 +123,20 @@ internal extension NSManagedObjectContext {
let saveError = CoreStoreError(error)
CoreStore.log(
saveError,
"Failed to save \(cs_typeName(NSManagedObjectContext))."
"Failed to save \(cs_typeName(NSManagedObjectContext.self))."
)
result = SaveResult(saveError)
return
}
if let parentContext = self.parentContext where self.shouldCascadeSavesToParent {
if let parentContext = self.parent where self.shouldCascadeSavesToParent {
switch parentContext.saveSynchronously() {
case .Success:
case .success:
result = SaveResult(hasChanges: true)
case .Failure(let error):
case .failure(let error):
result = SaveResult(error)
}
}
@@ -150,13 +150,13 @@ internal extension NSManagedObjectContext {
}
@nonobjc
internal func saveAsynchronouslyWithCompletion(completion: ((result: SaveResult) -> Void) = { _ in }) {
internal func saveAsynchronouslyWithCompletion(_ completion: ((result: SaveResult) -> Void) = { _ in }) {
self.performBlock {
self.perform {
guard self.hasChanges else {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(result: SaveResult(hasChanges: false))
}
@@ -174,22 +174,22 @@ internal extension NSManagedObjectContext {
let saveError = CoreStoreError(error)
CoreStore.log(
saveError,
"Failed to save \(cs_typeName(NSManagedObjectContext))."
"Failed to save \(cs_typeName(NSManagedObjectContext.self))."
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(result: SaveResult(saveError))
}
return
}
if let parentContext = self.parentContext where self.shouldCascadeSavesToParent {
if let parentContext = self.parent where self.shouldCascadeSavesToParent {
parentContext.saveAsynchronouslyWithCompletion(completion)
}
else {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(result: SaveResult(hasChanges: true))
}
@@ -206,7 +206,7 @@ internal extension NSManagedObjectContext {
}
else {
self.registeredObjects.forEach { self.refreshObject($0, mergeChanges: true) }
self.registeredObjects.forEach { self.refresh($0, mergeChanges: true) }
}
}
@@ -34,17 +34,17 @@ internal extension NSManagedObjectModel {
// MARK: Internal
@nonobjc
internal static func fromBundle(bundle: NSBundle, 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 {
CoreStore.abort("Could not find \"\(modelName).momd\" from the bundle. \(bundle)")
}
let modelFileURL = NSURL(fileURLWithPath: modelFilePath)
let versionInfoPlistURL = modelFileURL.URLByAppendingPathComponent("VersionInfo.plist", isDirectory: false)
let modelFileURL = URL(fileURLWithPath: modelFilePath)
let versionInfoPlistURL = try! modelFileURL.appendingPathComponent("VersionInfo.plist", isDirectory: false)
guard let versionInfo = NSDictionary(contentsOfURL: versionInfoPlistURL),
guard let versionInfo = NSDictionary(contentsOf: versionInfoPlistURL),
let versionHashes = versionInfo["NSManagedObjectModel_VersionHashes"] as? [String: AnyObject] else {
CoreStore.abort("Could not load \(cs_typeName(NSManagedObjectModel)) metadata from path \"\(versionInfoPlistURL)\".")
@@ -56,10 +56,10 @@ internal extension NSManagedObjectModel {
currentModelVersion = plistModelVersion
}
else if let resolvedVersion = modelVersions.intersect(modelVersionHints).first {
else if let resolvedVersion = modelVersions.intersection(modelVersionHints).first {
CoreStore.log(
.Warning,
.warning,
message: "The MigrationChain leaf versions do not include the model file's current version. Resolving to version \"\(resolvedVersion)\"."
)
currentModelVersion = resolvedVersion
@@ -69,7 +69,7 @@ internal extension NSManagedObjectModel {
if !modelVersionHints.isEmpty {
CoreStore.log(
.Warning,
.warning,
message: "The MigrationChain leaf versions do not include any of the model file's embedded versions. Resolving to version \"\(resolvedVersion)\"."
)
}
@@ -80,10 +80,10 @@ internal extension NSManagedObjectModel {
CoreStore.abort("No model files were found in URL \"\(modelFileURL)\".")
}
var modelVersionFileURL: NSURL?
var modelVersionFileURL: URL?
for modelVersion in modelVersions {
let fileURL = modelFileURL.URLByAppendingPathComponent("\(modelVersion).mom", isDirectory: false)
let fileURL = try! modelFileURL.appendingPathComponent("\(modelVersion).mom", isDirectory: false)
if modelVersion == currentModelVersion {
@@ -92,13 +92,13 @@ internal extension NSManagedObjectModel {
}
precondition(
NSManagedObjectModel(contentsOfURL: fileURL) != nil,
NSManagedObjectModel(contentsOf: fileURL) != nil,
"Could not find the \"\(modelVersion).mom\" version file for the model at URL \"\(modelFileURL)\"."
)
}
if let modelVersionFileURL = modelVersionFileURL,
let rootModel = NSManagedObjectModel(contentsOfURL: modelVersionFileURL) {
let rootModel = NSManagedObjectModel(contentsOf: modelVersionFileURL) {
rootModel.modelVersionFileURL = modelVersionFileURL
rootModel.modelVersions = modelVersions
@@ -152,7 +152,7 @@ internal extension NSManagedObjectModel {
}
@nonobjc
internal func entityNameForClass(entityClass: AnyClass) -> String {
internal func entityNameForClass(_ entityClass: AnyClass) -> String {
return self.entityNameMapping[NSStringFromClass(entityClass)]!
}
@@ -189,8 +189,8 @@ internal extension NSManagedObjectModel {
return nil
}
let versionModelFileURL = modelFileURL.URLByAppendingPathComponent("\(modelVersion).mom", isDirectory: false)
guard let model = NSManagedObjectModel(contentsOfURL: versionModelFileURL) else {
let versionModelFileURL = try! modelFileURL.appendingPathComponent("\(modelVersion).mom", isDirectory: false)
guard let model = NSManagedObjectModel(contentsOf: versionModelFileURL) else {
return nil
}
@@ -204,7 +204,7 @@ internal extension NSManagedObjectModel {
@nonobjc
internal subscript(metadata: [String: AnyObject]) -> NSManagedObjectModel? {
guard let modelHashes = metadata[NSStoreModelVersionHashesKey] as? [String : NSData] else {
guard let modelHashes = metadata[NSStoreModelVersionHashesKey] as? [String : Data] else {
return nil
}
@@ -222,16 +222,16 @@ internal extension NSManagedObjectModel {
// MARK: Private
@nonobjc
private var modelFileURL: NSURL? {
private var modelFileURL: URL? {
get {
return self.modelVersionFileURL?.URLByDeletingLastPathComponent
return try! self.modelVersionFileURL?.deletingLastPathComponent()
}
}
@nonobjc
private var modelVersionFileURL: NSURL? {
private var modelVersionFileURL: URL? {
get {
@@ -239,12 +239,12 @@ internal extension NSManagedObjectModel {
&PropertyKeys.modelVersionFileURL,
inObject: self
)
return value
return value as URL?
}
set {
cs_setAssociatedCopiedObject(
newValue,
newValue as NSURL?,
forKey: &PropertyKeys.modelVersionFileURL,
inObject: self
)
@@ -270,7 +270,7 @@ internal extension NSManagedObjectModel {
}
let className = $0.managedObjectClassName
mapping[className] = entityName
mapping[className!] = entityName
}
cs_setAssociatedCopiedObject(
mapping as NSDictionary,
@@ -36,124 +36,47 @@ import CoreData
internal extension NSPersistentStoreCoordinator {
@nonobjc
internal func performAsynchronously(closure: () -> Void) {
internal func performAsynchronously(_ closure: () -> Void) {
#if USE_FRAMEWORKS
self.performBlock(closure)
#else
if #available(iOS 8.0, *) {
self.performBlock(closure)
}
else {
self.lock()
GCDQueue.Default.async {
closure()
self.unlock()
}
}
#endif
self.perform(closure)
}
@nonobjc
internal func performSynchronously<T>(closure: () -> T) -> T {
internal func performSynchronously<T>(_ closure: () -> T) -> T {
var result: T?
#if USE_FRAMEWORKS
self.performAndWait {
self.performBlockAndWait {
result = closure()
}
#else
if #available(iOS 8.0, *) {
self.performBlockAndWait {
result = closure()
}
}
else {
self.lock()
cs_autoreleasepool {
result = closure()
}
self.unlock()
}
#endif
result = closure()
}
return result!
}
@nonobjc
internal func performSynchronously<T>(closure: () throws -> T) throws -> T {
internal func performSynchronously<T>(_ closure: () throws -> T) throws -> T {
var closureError: ErrorType?
var closureError: ErrorProtocol?
var result: T?
#if USE_FRAMEWORKS
self.performAndWait {
self.performBlockAndWait {
do {
do {
result = try closure()
}
catch {
closureError = error
}
result = try closure()
}
#else
if #available(iOS 8.0, *) {
catch {
self.performBlockAndWait {
do {
result = try closure()
}
catch {
closureError = error
}
}
closureError = error
}
else {
self.lock()
cs_autoreleasepool {
do {
result = try closure()
}
catch {
closureError = error
}
}
self.unlock()
}
#endif
}
if let closureError = closureError {
throw closureError
}
return result!
}
@nonobjc
internal func addPersistentStoreSynchronously(storeType: String, configuration: String?, URL storeURL: NSURL?, options: [NSObject : AnyObject]?) throws -> NSPersistentStore {
internal func addPersistentStoreSynchronously(_ storeType: String, configuration: String?, URL storeURL: URL?, options: [NSObject : AnyObject]?) throws -> NSPersistentStore {
var store: NSPersistentStore?
var storeError: NSError?
@@ -161,10 +84,10 @@ internal extension NSPersistentStoreCoordinator {
do {
store = try self.addPersistentStoreWithType(
storeType,
configuration: configuration,
URL: storeURL,
store = try self.addPersistentStore(
ofType: storeType,
configurationName: configuration,
at: storeURL,
options: options
)
}
@@ -173,12 +96,10 @@ internal extension NSPersistentStoreCoordinator {
storeError = error as NSError
}
}
if let store = store {
return store
}
throw CoreStoreError(storeError)
}
}
}
+6 -6
View File
@@ -36,23 +36,23 @@ internal final class NotificationObserver {
let object: AnyObject?
let observer: NSObjectProtocol
init(notificationName: String, object: AnyObject?, queue: NSOperationQueue? = nil, closure: (note: NSNotification) -> Void) {
init(notificationName: String, object: AnyObject?, queue: OperationQueue? = nil, closure: (note: Notification) -> Void) {
self.notificationName = notificationName
self.object = object
self.observer = NSNotificationCenter.defaultCenter().addObserverForName(
notificationName,
self.observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name(rawValue: notificationName),
object: object,
queue: queue,
usingBlock: closure
using: closure
)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
NotificationCenter.default.removeObserver(
self.observer,
name: self.notificationName,
name: NSNotification.Name(rawValue: self.notificationName),
object: self.object
)
}
@@ -72,27 +72,27 @@ extension CloudStorageOptions: CustomDebugStringConvertible, CoreStoreDebugStrin
public var coreStoreDumpString: String {
var flags = [String]()
if self.contains(.RecreateLocalStoreOnModelMismatch) {
if self.contains(.recreateLocalStoreOnModelMismatch) {
flags.append(".RecreateLocalStoreOnModelMismatch")
flags.append(".recreateLocalStoreOnModelMismatch")
}
if self.contains(.AllowSynchronousLightweightMigration) {
if self.contains(.allowSynchronousLightweightMigration) {
flags.append(".AllowSynchronousLightweightMigration")
flags.append(".allowSynchronousLightweightMigration")
}
switch flags.count {
case 0:
return "[.None]"
return "[.none]"
case 1:
return "[.\(flags[0])]"
default:
var string = "[\n"
string.appendContentsOf(flags.joinWithSeparator(",\n"))
string.append(flags.joined(separator: ",\n"))
string.indent(1)
string.appendContentsOf("\n]")
string.append("\n]")
return string
}
}
@@ -122,25 +122,25 @@ extension CoreStoreError: CustomDebugStringConvertible, CoreStoreDebugStringConv
]
switch self {
case .Unknown:
firstLine = ".Unknown"
case .unknown:
firstLine = ".unknown"
case .DifferentStorageExistsAtURL(let existingPersistentStoreURL):
firstLine = ".DifferentStorageExistsAtURL"
case .differentStorageExistsAtURL(let existingPersistentStoreURL):
firstLine = ".differentStorageExistsAtURL"
info.append(("existingPersistentStoreURL", existingPersistentStoreURL))
case .MappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
firstLine = ".MappingModelNotFound"
case .mappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
firstLine = ".mappingModelNotFound"
info.append(("localStoreURL", localStoreURL))
info.append(("targetModel", targetModel))
info.append(("targetModelVersion", targetModelVersion))
case .ProgressiveMigrationRequired(let localStoreURL):
firstLine = ".ProgressiveMigrationRequired"
case .progressiveMigrationRequired(let localStoreURL):
firstLine = ".progressiveMigrationRequired"
info.append(("localStoreURL", localStoreURL))
case .InternalError(let NSError):
firstLine = ".InternalError"
case .internalError(let NSError):
firstLine = ".internalError"
info.append(("NSError", NSError))
}
@@ -404,31 +404,31 @@ extension LocalStorageOptions: CustomDebugStringConvertible, CoreStoreDebugStrin
public var coreStoreDumpString: String {
var flags = [String]()
if self.contains(.RecreateStoreOnModelMismatch) {
if self.contains(.recreateStoreOnModelMismatch) {
flags.append(".RecreateStoreOnModelMismatch")
flags.append(".recreateStoreOnModelMismatch")
}
if self.contains(.PreventProgressiveMigration) {
if self.contains(.preventProgressiveMigration) {
flags.append(".PreventProgressiveMigration")
flags.append(".preventProgressiveMigration")
}
if self.contains(.AllowSynchronousLightweightMigration) {
if self.contains(.allowSynchronousLightweightMigration) {
flags.append(".AllowSynchronousLightweightMigration")
flags.append(".allowSynchronousLightweightMigration")
}
switch flags.count {
case 0:
return "[.None]"
return "[.none]"
case 1:
return "[.\(flags[0])]"
default:
var string = "[\n"
string.appendContentsOf(flags.joinWithSeparator(",\n"))
string.append(flags.joined(separator: ",\n"))
string.indent(1)
string.appendContentsOf("\n]")
string.append("\n]")
return string
}
}
@@ -465,7 +465,7 @@ extension MigrationChain: CustomDebugStringConvertible, CoreStoreDebugStringConv
steps.append(nextVersion)
version = nextVersion
}
paths.append(steps.joinWithSeparator(""))
paths.append(steps.joined(separator: ""))
}
switch paths.count {
@@ -479,10 +479,10 @@ extension MigrationChain: CustomDebugStringConvertible, CoreStoreDebugStringConv
var string = "["
paths.forEach {
string.appendContentsOf("\n\($0);")
string.append("\n\($0);")
}
string.indent(1)
string.appendContentsOf("\n]")
string.append("\n]")
return string
}
}
@@ -507,15 +507,15 @@ extension MigrationResult: CustomDebugStringConvertible, CoreStoreDebugStringCon
switch self {
case .Success(let migrationTypes):
case .success(let migrationTypes):
return createFormattedString(
".Success (", ")",
".success (", ")",
("migrationTypes", migrationTypes)
)
case .Failure(let error):
case .failure(let error):
return createFormattedString(
".Failure (", ")",
".failure (", ")",
("error", error)
)
}
@@ -541,14 +541,14 @@ extension MigrationType: CustomDebugStringConvertible, CoreStoreDebugStringConve
switch self {
case .None(let version):
return ".None (\"\(version)\")"
case .none(let version):
return ".none (\"\(version)\")"
case .Lightweight(let sourceVersion, let destinationVersion):
return ".Lightweight (\"\(sourceVersion)\"\"\(destinationVersion)\")"
case .lightweight(let sourceVersion, let destinationVersion):
return ".lightweight (\"\(sourceVersion)\"\"\(destinationVersion)\")"
case .Heavyweight(let sourceVersion, let destinationVersion):
return ".Heavyweight (\"\(sourceVersion)\"\"\(destinationVersion)\")"
case .heavyweight(let sourceVersion, let destinationVersion):
return ".heavyweight (\"\(sourceVersion)\"\"\(destinationVersion)\")"
}
}
}
@@ -623,15 +623,15 @@ extension SaveResult: CustomDebugStringConvertible, CoreStoreDebugStringConverti
switch self {
case .Success(let hasChanges):
case .success(let hasChanges):
return createFormattedString(
".Success (", ")",
".success (", ")",
("hasChanges", hasChanges)
)
case .Failure(let error):
case .failure(let error):
return createFormattedString(
".Failure (", ")",
".failure (", ")",
("error", error)
)
}
@@ -708,24 +708,24 @@ extension SelectTerm: CustomDebugStringConvertible, CoreStoreDebugStringConverti
switch self {
case ._Attribute(let keyPath):
case ._attribute(let keyPath):
return createFormattedString(
".Attribute (", ")",
("keyPath", keyPath)
)
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
case ._aggregate(let function, let keyPath, let alias, let nativeType):
return createFormattedString(
".Aggregate (", ")",
".aggregate (", ")",
("function", function),
("keyPath", keyPath),
("alias", alias),
("nativeType", nativeType)
)
case ._Identity(let alias, let nativeType):
case ._identity(let alias, let nativeType):
return createFormattedString(
".Identity (", ")",
".identity (", ")",
("alias", alias),
("nativeType", nativeType)
)
@@ -752,15 +752,15 @@ extension SetupResult: CustomDebugStringConvertible, CoreStoreDebugStringConvert
switch self {
case .Success(let storage):
case .success(let storage):
return createFormattedString(
".Success (", ")",
".success (", ")",
("storage", storage)
)
case .Failure(let error):
case .failure(let error):
return createFormattedString(
".Failure (", ")",
".failure (", ")",
("error", error)
)
}
@@ -898,7 +898,7 @@ extension Where: CustomDebugStringConvertible, CoreStoreDebugStringConvertible {
private typealias DumpInfo = [(key: String, value: Any)]
private func formattedValue(any: Any) -> String {
private func formattedValue(_ any: Any) -> String {
switch any {
@@ -910,19 +910,19 @@ private func formattedValue(any: Any) -> String {
}
}
private func formattedDebugDescription(any: Any) -> String {
private func formattedDebugDescription(_ any: Any) -> String {
var string = "(\(String(reflecting: any.dynamicType))) "
string.appendContentsOf(formattedValue(any))
string.append(formattedValue(any))
return string
}
private func createFormattedString(firstLine: String, _ lastLine: String, _ info: (key: String, value: Any)...) -> String {
private func createFormattedString(_ firstLine: String, _ lastLine: String, _ info: (key: String, value: Any)...) -> String {
return createFormattedString(firstLine, lastLine, info)
}
private func createFormattedString(firstLine: String, _ lastLine: String, _ info: [(key: String, value: Any)]) -> String {
private func createFormattedString(_ firstLine: String, _ lastLine: String, _ info: [(key: String, value: Any)]) -> String {
var string = firstLine
for (key, value) in info {
@@ -930,34 +930,34 @@ private func createFormattedString(firstLine: String, _ lastLine: String, _ info
string.appendDumpInfo(key, value)
}
string.indent(1)
string.appendContentsOf("\n\(lastLine)")
string.append("\n\(lastLine)")
return string
}
private extension String {
private static func indention(level: Int = 1) -> String {
private static func indention(_ level: Int = 1) -> String {
return String(count: level * 4, repeatedValue: Character(" "))
return String(repeating: Character(" "), count: level * 4)
}
private func trimSwiftModuleName() -> String {
if self.hasPrefix("Swift.") {
return self.substringFromIndex("Swift.".endIndex)
return self.substring(from: "Swift.".endIndex)
}
return self
}
private mutating func indent(level: Int) {
private mutating func indent(_ level: Int) {
self = self.stringByReplacingOccurrencesOfString("\n", withString: "\n\(String.indention(level))")
self = self.replacingOccurrences(of: "\n", with: "\n\(String.indention(level))")
}
private mutating func appendDumpInfo(key: String, _ value: Any) {
private mutating func appendDumpInfo(_ key: String, _ value: Any) {
self.appendContentsOf("\n.\(key) = \(formattedValue(value));")
self.append("\n.\(key) = \(formattedValue(value));")
}
}
@@ -979,17 +979,17 @@ extension Array: CoreStoreDebugStringConvertible {
var string = "\(self.count) item(s) ["
if self.isEmpty {
string.appendContentsOf("]")
string.append("]")
return string
}
else {
for (index, item) in self.enumerate() {
for (index, item) in self.enumerated() {
string.appendContentsOf("\n\(index) = \(formattedValue(item));")
string.append("\n\(index) = \(formattedValue(item));")
}
string.indent(1)
string.appendContentsOf("\n]")
string.append("\n]")
return string
}
}
@@ -1002,17 +1002,17 @@ extension Dictionary: CoreStoreDebugStringConvertible {
var string = "\(self.count) key-value(s) ["
if self.isEmpty {
string.appendContentsOf("]")
string.append("]")
return string
}
else {
for (key, value) in self {
string.appendContentsOf("\n\(formattedValue(key)) = \(formattedValue(value));")
string.append("\n\(formattedValue(key)) = \(formattedValue(value));")
}
string.indent(1)
string.appendContentsOf("\n]")
string.append("\n]")
return string
}
}
@@ -1031,14 +1031,14 @@ extension NSAttributeDescription: CoreStoreDebugStringConvertible {
("allowsExternalBinaryDataStorage", self.allowsExternalBinaryDataStorage),
("entity.name", self.entity.name),
("name", self.name),
("optional", self.optional),
("transient", self.transient),
("isOptional", self.isOptional),
("isTransient", self.isTransient),
("userInfo", self.userInfo),
("indexed", self.indexed),
("isIndexed", self.isIndexed),
("versionHash", self.versionHash),
("versionHashModifier", self.versionHashModifier),
("indexedBySpotlight", self.indexedBySpotlight),
("storedInExternalRecord", self.storedInExternalRecord),
("isIndexedBySpotlight", self.isIndexedBySpotlight),
("isStoredInExternalRecord", self.isStoredInExternalRecord),
("renamingIdentifier", self.renamingIdentifier)
)
}
@@ -1050,24 +1050,24 @@ extension NSAttributeType: CoreStoreDebugStringConvertible {
switch self {
case .UndefinedAttributeType: return ".UndefinedAttributeType"
case .Integer16AttributeType: return ".Integer16AttributeType"
case .Integer32AttributeType: return ".Integer32AttributeType"
case .Integer64AttributeType: return ".Integer64AttributeType"
case .DecimalAttributeType: return ".DecimalAttributeType"
case .DoubleAttributeType: return ".DoubleAttributeType"
case .FloatAttributeType: return ".FloatAttributeType"
case .StringAttributeType: return ".StringAttributeType"
case .BooleanAttributeType: return ".BooleanAttributeType"
case .DateAttributeType: return ".DateAttributeType"
case .BinaryDataAttributeType: return ".BinaryDataAttributeType"
case .TransformableAttributeType: return ".TransformableAttributeType"
case .ObjectIDAttributeType: return ".ObjectIDAttributeType"
case .undefinedAttributeType: return ".undefinedAttributeType"
case .integer16AttributeType: return ".integer16AttributeType"
case .integer32AttributeType: return ".integer32AttributeType"
case .integer64AttributeType: return ".integer64AttributeType"
case .decimalAttributeType: return ".decimalAttributeType"
case .doubleAttributeType: return ".doubleAttributeType"
case .floatAttributeType: return ".floatAttributeType"
case .stringAttributeType: return ".stringAttributeType"
case .booleanAttributeType: return ".booleanAttributeType"
case .dateAttributeType: return ".dateAttributeType"
case .binaryDataAttributeType: return ".binaryDataAttributeType"
case .transformableAttributeType: return ".transformableAttributeType"
case .objectIDAttributeType: return ".objectIDAttributeType"
}
}
}
extension NSBundle: CoreStoreDebugStringConvertible {
extension Bundle: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
@@ -1081,10 +1081,10 @@ extension NSDeleteRule: CoreStoreDebugStringConvertible {
switch self {
case .NoActionDeleteRule: return ".NoActionDeleteRule"
case .NullifyDeleteRule: return ".NullifyDeleteRule"
case .CascadeDeleteRule: return ".CascadeDeleteRule"
case .DenyDeleteRule: return ".DenyDeleteRule"
case .noActionDeleteRule: return ".noActionDeleteRule"
case .nullifyDeleteRule: return ".nullifyDeleteRule"
case .cascadeDeleteRule: return ".cascadeDeleteRule"
case .denyDeleteRule: return ".denyDeleteRule"
}
}
}
@@ -1096,7 +1096,7 @@ extension NSEntityDescription: CoreStoreDebugStringConvertible {
var info: DumpInfo = [
("managedObjectClassName", self.managedObjectClassName!),
("name", self.name),
("abstract", self.abstract),
("isAbstract", self.isAbstract),
("superentity?.name", self.superentity?.name),
("subentities", self.subentities.map({ $0.name })),
("properties", self.properties),
@@ -1147,10 +1147,10 @@ extension NSManagedObjectID: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
return createFormattedString(
"\(self.URIRepresentation().coreStoreDumpString) (", ")",
"\(self.uriRepresentation().coreStoreDumpString) (", ")",
("entity.name", self.entity.name),
("temporaryID", self.temporaryID),
("persistentStore?.URL", self.persistentStore?.URL)
("isTemporaryID", self.isTemporaryID),
("persistentStore?.url", self.persistentStore?.url)
)
}
}
@@ -1163,7 +1163,7 @@ extension NSMappingModel: CoreStoreDebugStringConvertible {
}
}
extension NSPredicate: CoreStoreDebugStringConvertible {
extension Predicate: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
@@ -1182,24 +1182,24 @@ extension NSRelationshipDescription: CoreStoreDebugStringConvertible {
("minCount", self.minCount),
("maxCount", self.maxCount),
("deleteRule", self.deleteRule),
("toMany", self.toMany),
("ordered", self.ordered),
("isToMany", self.isToMany),
("isOrdered", self.isOrdered),
("entity.name", self.entity.name),
("name", self.name),
("optional", self.optional),
("transient", self.transient),
("isOptional", self.isOptional),
("isTransient", self.isTransient),
("userInfo", self.userInfo),
("indexed", self.indexed),
("isIndexed", self.isIndexed),
("versionHash", self.versionHash),
("versionHashModifier", self.versionHashModifier),
("indexedBySpotlight", self.indexedBySpotlight),
("storedInExternalRecord", self.storedInExternalRecord),
("isIndexedBySpotlight", self.isIndexedBySpotlight),
("isStoredInExternalRecord", self.isStoredInExternalRecord),
("renamingIdentifier", self.renamingIdentifier)
)
}
}
extension NSSortDescriptor: CoreStoreDebugStringConvertible {
extension SortDescriptor: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
@@ -1212,7 +1212,7 @@ extension NSSortDescriptor: CoreStoreDebugStringConvertible {
}
}
extension NSURL: CoreStoreDebugStringConvertible {
extension URL: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
@@ -1236,7 +1236,7 @@ extension Selector: CoreStoreDebugStringConvertible {
public var coreStoreDumpString: String {
return self == nil ? "nil" : "\"\(self)\""
return "\"\(self)\""
}
}
+4 -4
View File
@@ -38,7 +38,7 @@ public extension CoreStore {
// MARK: Internal
internal static func log(level: LogLevel, message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
internal static func log(_ level: LogLevel, message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
self.logger.log(
level: level,
@@ -49,7 +49,7 @@ public extension CoreStore {
)
}
internal static func log(error: CoreStoreError, _ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
internal static func log(_ error: CoreStoreError, _ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
self.logger.log(
error: error,
@@ -60,7 +60,7 @@ public extension CoreStore {
)
}
internal static func assert(@autoclosure condition: () -> Bool, _ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
internal static func assert( _ condition: @autoclosure () -> Bool, _ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) {
self.logger.assert(
condition,
@@ -72,7 +72,7 @@ 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) {
self.logger.abort(
message,
+9 -27
View File
@@ -33,10 +33,10 @@ import Foundation
*/
public enum LogLevel {
case Trace
case Notice
case Warning
case Fatal
case trace
case notice
case warning
case fatal
}
@@ -56,7 +56,7 @@ public protocol CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
func log(level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
/**
Handles errors sent by the `CoreStore` framework.
@@ -67,7 +67,7 @@ public protocol CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
func log(error error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
func log(error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
/**
Handles assertions made throughout the `CoreStore` framework.
@@ -78,7 +78,7 @@ public protocol CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
func assert(@autoclosure condition: () -> Bool, @autoclosure message: () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
func assert(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
/**
Handles fatal errors made throughout the `CoreStore` framework. The app wil terminate after this method is called.
@@ -89,30 +89,12 @@ public protocol CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
func abort(message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
// MARK: Deprecated
/**
Deprecated. Use `log(error:message:fileName:lineNumber:functionName:)` instead.
*/
@available(*, deprecated=2.0.0, message="Use log(error:message:fileName:lineNumber:functionName:) instead.")
func handleError(error error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
}
extension CoreStoreLogger {
/**
Deprecated. Use `log(error:message:fileName:lineNumber:functionName:)` instead.
*/
@available(*, deprecated=2.0.0, message="Use log(error:message:fileName:lineNumber:functionName:) instead.")
public func handleError(error error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
self.log(error: error.bridgeToSwift, message: message, fileName: fileName, lineNumber: lineNumber, functionName: functionName)
}
public func abort(message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
public func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
Swift.fatalError(message, file: fileName, line: UInt(lineNumber))
}
+12 -12
View File
@@ -51,30 +51,30 @@ public final class DefaultLogger: CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
public func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
public func log(level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
#if DEBUG
let icon: String
let levelString: String
switch level {
case .Trace:
case .trace:
icon = "🔹"
levelString = "Trace"
case .Notice:
case .notice:
icon = "🔸"
levelString = "Notice"
case .Warning:
case .warning:
icon = "⚠️"
levelString = "Warning"
case .Fatal:
case .fatal:
icon = ""
levelString = "Fatal"
}
Swift.print("\(icon) [CoreStore: \(levelString)] \((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
Swift.print("\(icon) [CoreStore: \(levelString)] \((String(fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
#endif
}
@@ -87,10 +87,10 @@ public final class DefaultLogger: CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
public func log(error error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
public func log(error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
#if DEBUG
Swift.print("⚠️ [CoreStore: Error] \((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n \(error)\n")
Swift.print("⚠️ [CoreStore: Error] \((String(fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n \(error)\n")
#endif
}
@@ -103,14 +103,14 @@ public final class DefaultLogger: CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
public func assert(@autoclosure condition: () -> Bool, @autoclosure message: () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
public func assert(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
#if DEBUG
if condition() {
return
}
Swift.print("❗ [CoreStore: Assertion Failure] \((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message())\n")
Swift.print("❗ [CoreStore: Assertion Failure] \((String(fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message())\n")
Swift.fatalError(file: fileName, line: UInt(lineNumber))
#endif
}
@@ -124,9 +124,9 @@ public final class DefaultLogger: CoreStoreLogger {
- parameter lineNumber: the source line number
- parameter functionName: the source function name
*/
public func abort(message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
public func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
Swift.print("❗ [CoreStore: Fatal Error] \((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
Swift.print("❗ [CoreStore: Fatal Error] \((String(fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
Swift.fatalError(file: fileName, line: UInt(lineNumber))
}
}
+8 -109
View File
@@ -51,7 +51,7 @@ public extension CoreStore {
- 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.
*/
public static func addStorage<T: StorageInterface where T: DefaultInitializableStore>(storeType: T.Type, completion: (SetupResult<T>) -> Void) {
public static func addStorage<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) {
self.defaultStack.addStorage(storeType.init(), completion: completion)
}
@@ -73,7 +73,7 @@ public extension CoreStore {
- 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.
*/
public static func addStorage<T: StorageInterface>(storage: T, completion: (SetupResult<T>) -> Void) {
public static func addStorage<T: StorageInterface>(_ storage: T, completion: (SetupResult<T>) -> Void) {
self.defaultStack.addStorage(storage, completion: completion)
}
@@ -96,7 +96,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.
- 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) -> NSProgress? {
public static func addStorage<T: LocalStorage where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? {
return self.defaultStack.addStorage(storeType.init(), completion: completion)
}
@@ -119,7 +119,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.
- 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>(storage: T, completion: (SetupResult<T>) -> Void) -> NSProgress? {
public static func addStorage<T: LocalStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) -> Progress? {
return self.defaultStack.addStorage(storage, completion: completion)
}
@@ -133,7 +133,7 @@ public extension CoreStore {
ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername",
ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0",
configuration: "Config1",
cloudStorageOptions: .RecreateLocalStoreOnModelMismatch
cloudStorageOptions: .recreateLocalStoreOnModelMismatch
) else {
// iCloud is not available on the device
return
@@ -152,7 +152,7 @@ public extension CoreStore {
- 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.
*/
public static func addStorage<T: CloudStorage>(storage: T, completion: (SetupResult<T>) -> Void) {
public static func addStorage<T: CloudStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) {
self.defaultStack.addStorage(storage, completion: completion)
}
@@ -165,7 +165,7 @@ public extension CoreStore {
- throws: a `CoreStoreError` value indicating the failure
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public static func upgradeStorageIfNeeded<T: LocalStorage>(storage: T, completion: (MigrationResult) -> Void) throws -> NSProgress? {
public static func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, completion: (MigrationResult) -> Void) throws -> Progress? {
return try self.defaultStack.upgradeStorageIfNeeded(storage, completion: completion)
}
@@ -178,109 +178,8 @@ public extension CoreStore {
- returns: a `MigrationType` array indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, an error is thrown if either inspection of the store failed, or if no mapping model was found/inferred.
*/
@warn_unused_result
public static func requiredMigrationsForStorage<T: LocalStorage>(storage: T) throws -> [MigrationType] {
public static func requiredMigrationsForStorage<T: LocalStorage>(_ storage: T) throws -> [MigrationType] {
return try self.defaultStack.requiredMigrationsForStorage(storage)
}
// MARK: Deprecated
/**
Deprecated. Use `addSQLiteStore(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addSQLiteStore(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.addSQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
resetStoreOnModelMismatch: resetStoreOnModelMismatch,
completion: completion
)
}
/**
Deprecated. Use `addSQLiteStore(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addSQLiteStore(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func addSQLiteStore(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.addSQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
resetStoreOnModelMismatch: resetStoreOnModelMismatch,
completion: completion
)
}
/**
Deprecated. Use `upgradeStorageIfNeeded(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use upgradeStorageIfNeeded(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.upgradeSQLiteStoreIfNeeded(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
completion: completion
)
}
/**
Deprecated. Use `upgradeStorageIfNeeded(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use upgradeStorageIfNeeded(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.upgradeSQLiteStoreIfNeeded(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
completion: completion
)
}
/**
Deprecated. Use `requiredMigrationsForStorage(_:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use requiredMigrationsForStorage(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
@warn_unused_result
public static func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
return try self.defaultStack.requiredMigrationsForSQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles
)
}
/**
Deprecated. Use `requiredMigrationsForStorage(_:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use requiredMigrationsForStorage(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
@warn_unused_result
public static func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
return try self.defaultStack.requiredMigrationsForSQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles
)
}
}
+106 -262
View File
@@ -51,7 +51,7 @@ public extension DataStack {
- 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.
*/
public func addStorage<T: StorageInterface where T: DefaultInitializableStore>(storeType: T.Type, completion: (SetupResult<T>) -> Void) {
public func addStorage<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) {
self.addStorage(storeType.init(), completion: completion)
}
@@ -73,13 +73,13 @@ public extension DataStack {
- 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.
*/
public func addStorage<T: StorageInterface>(storage: T, completion: (SetupResult<T>) -> Void) {
public func addStorage<T: StorageInterface>(_ storage: T, completion: (SetupResult<T>) -> Void) {
self.coordinator.performAsynchronously {
if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
@@ -94,7 +94,7 @@ public extension DataStack {
finalStoreOptions: storage.storeOptions
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
@@ -106,7 +106,7 @@ public extension DataStack {
storeError,
"Failed to add \(cs_typeName(storage)) to the stack."
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storeError))
}
@@ -132,7 +132,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.
- 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) -> NSProgress? {
public func addStorage<T: LocalStorage where T: DefaultInitializableStore>(_ storeType: T.Type, completion: (SetupResult<T>) -> Void) -> Progress? {
return self.addStorage(storeType.init(), completion: completion)
}
@@ -155,11 +155,11 @@ 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.
- 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) -> NSProgress? {
public func addStorage<T: LocalStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) -> Progress? {
let fileURL = storage.fileURL
CoreStore.assert(
fileURL.fileURL,
fileURL.isFileURL,
"The specified URL for the \(cs_typeName(storage)) is invalid: \"\(fileURL)\""
)
@@ -167,31 +167,31 @@ public extension DataStack {
if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
return nil
}
if let persistentStore = self.coordinator.persistentStoreForURL(fileURL) {
if let persistentStore = self.coordinator.persistentStore(for: fileURL as URL) {
if let existingStorage = persistentStore.storageInterface as? T
where storage.matchesPersistentStore(persistentStore) {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(existingStorage))
}
return nil
}
let error = CoreStoreError.DifferentStorageExistsAtURL(existingPersistentStoreURL: fileURL)
let error = CoreStoreError.differentStorageExistsAtURL(existingPersistentStoreURL: fileURL)
CoreStore.log(
error,
"Failed to add \(cs_typeName(storage)) at \"\(fileURL)\" because a different \(cs_typeName(NSPersistentStore)) 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 {
GCDQueue.main.async {
completion(SetupResult(error))
}
@@ -200,15 +200,15 @@ public extension DataStack {
do {
try NSFileManager.defaultManager().createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
try FileManager.default.createDirectory(
at: try fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: fileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: fileURL as URL,
options: storage.storeOptions
)
@@ -217,16 +217,16 @@ public extension DataStack {
metadata: metadata,
completion: { (result) -> Void in
if case .Failure(.InternalError(let error)) = result {
if case .failure(.internalError(let error)) = result {
if storage.localStorageOptions.contains(.RecreateStoreOnModelMismatch) && error.isCoreDataMigrationError {
if storage.localStorageOptions.contains(.recreateStoreOnModelMismatch) && error.isCoreDataMigrationError {
do {
try _ = self.model[metadata].flatMap(storage.eraseStorageAndWait)
try self.addStorageAndWait(storage)
_ = try self.model[metadata].flatMap(storage.eraseStorageAndWait)
_ = try self.addStorageAndWait(storage)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
@@ -244,7 +244,7 @@ public extension DataStack {
do {
try self.addStorageAndWait(storage)
_ = try self.addStorageAndWait(storage)
completion(SetupResult(storage))
}
@@ -260,16 +260,16 @@ public extension DataStack {
do {
try self.addStorageAndWait(storage)
_ = try self.addStorageAndWait(storage)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
}
catch {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(error))
}
@@ -281,9 +281,9 @@ public extension DataStack {
let storeError = CoreStoreError(error)
CoreStore.log(
storeError,
"Failed to load SQLite \(cs_typeName(NSPersistentStore)) metadata."
"Failed to load SQLite \(cs_typeName(NSPersistentStore.self)) metadata."
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storeError))
}
@@ -301,7 +301,7 @@ public extension DataStack {
ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername",
ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0",
configuration: "Config1",
cloudStorageOptions: .RecreateLocalStoreOnModelMismatch
cloudStorageOptions: .recreateLocalStoreOnModelMismatch
) else {
// iCloud is not available on the device
return
@@ -320,38 +320,38 @@ public extension DataStack {
- 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.
*/
public func addStorage<T: CloudStorage>(storage: T, completion: (SetupResult<T>) -> Void) {
public func addStorage<T: CloudStorage>(_ storage: T, completion: (SetupResult<T>) -> Void) {
let cacheFileURL = storage.cacheFileURL
self.coordinator.performSynchronously {
if let _ = self.persistentStoreForStorage(storage) {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
return
}
if let persistentStore = self.coordinator.persistentStoreForURL(cacheFileURL) {
if let persistentStore = self.coordinator.persistentStore(for: cacheFileURL as URL) {
if let existingStorage = persistentStore.storageInterface as? T
where storage.matchesPersistentStore(persistentStore) {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(existingStorage))
}
return
}
let error = CoreStoreError.DifferentStorageExistsAtURL(existingPersistentStoreURL: cacheFileURL)
let error = CoreStoreError.differentStorageExistsAtURL(existingPersistentStoreURL: cacheFileURL)
CoreStore.log(
error,
"Failed to add \(cs_typeName(storage)) at \"\(cacheFileURL)\" because a different \(cs_typeName(NSPersistentStore)) 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 {
GCDQueue.main.async {
completion(SetupResult(error))
}
@@ -361,36 +361,35 @@ public extension DataStack {
do {
var cloudStorageOptions = storage.cloudStorageOptions
cloudStorageOptions.remove(.RecreateLocalStoreOnModelMismatch)
cloudStorageOptions.remove(.recreateLocalStoreOnModelMismatch)
let storeOptions = storage.storeOptionsForOptions(cloudStorageOptions)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(
cacheFileURL.URLByDeletingLastPathComponent!,
try FileManager.default.createDirectory(
at: try cacheFileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try self.createPersistentStoreFromStorage(
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: cacheFileURL,
finalStoreOptions: storeOptions
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
}
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.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: cacheFileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: cacheFileURL,
options: storeOptions
)
try _ = self.model[metadata].flatMap(storage.eraseStorageAndWait)
try self.createPersistentStoreFromStorage(
_ = try self.model[metadata].flatMap(storage.eraseStorageAndWait)
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: cacheFileURL,
finalStoreOptions: storeOptions
@@ -402,16 +401,16 @@ public extension DataStack {
do {
try self.addStorageAndWait(storage)
_ = try self.addStorageAndWait(storage)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storage))
}
}
catch {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(error))
}
@@ -424,7 +423,7 @@ public extension DataStack {
storeError,
"Failed to load \(cs_typeName(NSPersistentStore)) metadata."
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(SetupResult(storeError))
}
@@ -440,7 +439,7 @@ public extension DataStack {
- throws: a `CoreStoreError` value indicating the failure
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public func upgradeStorageIfNeeded<T: LocalStorage>(storage: T, completion: (MigrationResult) -> Void) throws -> NSProgress? {
public func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, completion: (MigrationResult) -> Void) throws -> Progress? {
return try self.coordinator.performSynchronously {
@@ -452,9 +451,9 @@ public extension DataStack {
"Attempted to migrate an already added \(cs_typeName(storage)) at URL \"\(fileURL)\""
)
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: fileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: fileURL as URL,
options: storage.storeOptions
)
return self.upgradeStorageIfNeeded(
@@ -483,7 +482,7 @@ public extension DataStack {
- returns: a `MigrationType` array indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, an error is thrown if either inspection of the store failed, or if no mapping model was found/inferred.
*/
@warn_unused_result
public func requiredMigrationsForStorage<T: LocalStorage>(storage: T) throws -> [MigrationType] {
public func requiredMigrationsForStorage<T: LocalStorage>(_ storage: T) throws -> [MigrationType] {
return try self.coordinator.performSynchronously {
@@ -495,15 +494,15 @@ public extension DataStack {
)
do {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: fileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: fileURL as URL,
options: storage.storeOptions
)
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else {
let error = CoreStoreError.MappingModelNotFound(
let error = CoreStoreError.mappingModelNotFound(
localStoreURL: fileURL,
targetModel: self.model,
targetModelVersion: self.modelVersion
@@ -515,9 +514,9 @@ public extension DataStack {
throw error
}
if migrationSteps.count > 1 && storage.localStorageOptions.contains(.PreventProgressiveMigration) {
if migrationSteps.count > 1 && storage.localStorageOptions.contains(.preventProgressiveMigration) {
let error = CoreStoreError.ProgressiveMigrationRequired(localStoreURL: fileURL)
let error = CoreStoreError.progressiveMigrationRequired(localStoreURL: fileURL)
CoreStore.log(
error,
"Failed to find migration mapping from the \(cs_typeName(storage)) at URL \"\(fileURL)\" to version model \"\(self.modelVersion)\" without requiring progessive migrations."
@@ -547,11 +546,11 @@ public extension DataStack {
// MARK: Private
private func upgradeStorageIfNeeded<T: LocalStorage>(storage: T, metadata: [String: AnyObject], completion: (MigrationResult) -> Void) -> NSProgress? {
private func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, metadata: [String: AnyObject], completion: (MigrationResult) -> Void) -> Progress? {
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else {
let error = CoreStoreError.MappingModelNotFound(
let error = CoreStoreError.mappingModelNotFound(
localStoreURL: storage.fileURL,
targetModel: self.model,
targetModelVersion: self.modelVersion
@@ -561,7 +560,7 @@ public extension DataStack {
"Failed to find migration steps from \(cs_typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.model)\"."
)
GCDQueue.Main.async {
GCDQueue.main.async {
completion(MigrationResult(error))
}
@@ -571,21 +570,21 @@ public extension DataStack {
let numberOfMigrations: Int64 = Int64(migrationSteps.count)
if numberOfMigrations == 0 {
GCDQueue.Main.async {
GCDQueue.main.async {
completion(MigrationResult([]))
return
}
return nil
}
else if numberOfMigrations > 1 && storage.localStorageOptions.contains(.PreventProgressiveMigration) {
else if numberOfMigrations > 1 && storage.localStorageOptions.contains(.preventProgressiveMigration) {
let error = CoreStoreError.ProgressiveMigrationRequired(localStoreURL: storage.fileURL)
let error = CoreStoreError.progressiveMigrationRequired(localStoreURL: storage.fileURL)
CoreStore.log(
error,
"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 {
GCDQueue.main.async {
completion(MigrationResult(error))
}
@@ -594,21 +593,21 @@ public extension DataStack {
let migrationTypes = migrationSteps.map { $0.migrationType }
var migrationResult: MigrationResult?
var operations = [NSOperation]()
var operations = [Operation]()
var cancelled = false
let progress = NSProgress(parent: nil, userInfo: nil)
let progress = Progress(parent: nil, userInfo: nil)
progress.totalUnitCount = numberOfMigrations
for (sourceModel, destinationModel, mappingModel, _) in migrationSteps {
progress.becomeCurrentWithPendingUnitCount(1)
progress.becomeCurrent(withPendingUnitCount: 1)
let childProgress = NSProgress(parent: progress, userInfo: nil)
let childProgress = Progress(parent: progress, userInfo: nil)
childProgress.totalUnitCount = 100
operations.append(
NSBlockOperation { [weak self] in
BlockOperation { [weak self] in
guard let `self` = self where !cancelled else {
@@ -634,9 +633,9 @@ public extension DataStack {
}
}
GCDQueue.Main.async {
GCDQueue.main.async {
_ = withExtendedLifetime(childProgress) { (_: NSProgress) -> Void in }
_ = withExtendedLifetime(childProgress) { (_: Progress) -> Void in }
}
}
)
@@ -644,21 +643,21 @@ public extension DataStack {
progress.resignCurrent()
}
let migrationOperation = NSBlockOperation()
let migrationOperation = BlockOperation()
#if USE_FRAMEWORKS
migrationOperation.qualityOfService = .Utility
migrationOperation.qualityOfService = .utility
#else
if #available(iOS 8.0, *) {
migrationOperation.qualityOfService = .Utility
migrationOperation.qualityOfService = .utility
}
#endif
operations.forEach { migrationOperation.addDependency($0) }
migrationOperation.addExecutionBlock { () -> Void in
GCDQueue.Main.async {
GCDQueue.main.async {
progress.setProgressHandler(nil)
completion(migrationResult ?? MigrationResult(migrationTypes))
@@ -673,10 +672,10 @@ public extension DataStack {
return progress
}
private func computeMigrationFromStorage<T: LocalStorage>(storage: T, metadata: [String: AnyObject]) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? {
private func computeMigrationFromStorage<T: LocalStorage>(_ storage: T, metadata: [String: AnyObject]) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? {
let model = self.model
if model.isConfiguration(storage.configuration, compatibleWithStoreMetadata: metadata) {
if model.isConfiguration(withName: storage.configuration, compatibleWithStoreMetadata: metadata) {
return []
}
@@ -698,7 +697,7 @@ public extension DataStack {
let destinationModel = model[nextVersion] where sourceModel != model {
if let mappingModel = NSMappingModel(
fromBundles: storage.mappingModelBundles,
from: storage.mappingModelBundles,
forSourceModel: sourceModel,
destinationModel: destinationModel) {
@@ -707,7 +706,7 @@ public extension DataStack {
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
migrationType: .Heavyweight(
migrationType: .heavyweight(
sourceVersion: currentVersion,
destinationVersion: nextVersion
)
@@ -718,8 +717,8 @@ public extension DataStack {
do {
let mappingModel = try NSMappingModel.inferredMappingModelForSourceModel(
sourceModel,
let mappingModel = try NSMappingModel.inferredMappingModel(
forSourceModel: sourceModel,
destinationModel: destinationModel
)
@@ -728,7 +727,7 @@ public extension DataStack {
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
migrationType: .Lightweight(
migrationType: .lightweight(
sourceVersion: currentVersion,
destinationVersion: nextVersion
)
@@ -751,22 +750,22 @@ public extension DataStack {
return nil
}
private func startMigrationForStorage<T: LocalStorage>(storage: T, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, progress: NSProgress) throws {
private func startMigrationForStorage<T: LocalStorage>(_ storage: T, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, progress: Progress) throws {
let fileURL = storage.fileURL
let temporaryDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.URLByAppendingPathComponent(NSBundle.mainBundle().bundleIdentifier ?? "com.CoreStore.DataStack")
.URLByAppendingPathComponent(NSProcessInfo().globallyUniqueString)
let temporaryDirectoryURL = try! URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent(Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack")
.appendingPathComponent(ProcessInfo().globallyUniqueString)
let fileManager = NSFileManager.defaultManager()
try! fileManager.createDirectoryAtURL(
temporaryDirectoryURL,
let fileManager = FileManager.default
try! fileManager.createDirectory(
at: temporaryDirectoryURL,
withIntermediateDirectories: true,
attributes: nil
)
let temporaryFileURL = temporaryDirectoryURL.URLByAppendingPathComponent(
let temporaryFileURL = try! temporaryDirectoryURL.appendingPathComponent(
fileURL.lastPathComponent!,
isDirectory: false
)
@@ -779,11 +778,11 @@ public extension DataStack {
do {
try migrationManager.migrateStoreFromURL(
fileURL,
type: storage.dynamicType.storeType,
try migrationManager.migrateStore(
from: fileURL,
sourceType: storage.dynamicType.storeType,
options: nil,
withMappingModel: mappingModel,
with: mappingModel,
toDestinationURL: temporaryFileURL,
destinationType: storage.dynamicType.storeType,
destinationOptions: nil
@@ -793,7 +792,7 @@ public extension DataStack {
do {
try fileManager.removeItemAtURL(temporaryFileURL)
try fileManager.removeItem(at: temporaryFileURL)
}
catch _ { }
@@ -810,9 +809,9 @@ public extension DataStack {
do {
try fileManager.replaceItemAtURL(
fileURL,
withItemAtURL: temporaryFileURL,
try fileManager.replaceItem(
at: fileURL as URL,
withItemAt: temporaryFileURL,
backupItemName: nil,
options: [],
resultingItemURL: nil
@@ -824,7 +823,7 @@ public extension DataStack {
do {
try fileManager.removeItemAtURL(temporaryFileURL)
try fileManager.removeItem(at: temporaryFileURL)
}
catch _ { }
@@ -839,159 +838,4 @@ public extension DataStack {
throw fileError
}
}
// MARK: Deprecated
/**
Deprecated. Use `addStorage(_:completion:)` by passing a `InMemoryStore` instance.
*/
@available(*, deprecated=2.0.0, message="Use addStorage(_:completion:) by passing a InMemoryStore instance.")
public func addInMemoryStore(configuration configuration: String? = nil, completion: (PersistentStoreResult) -> Void) {
self.addStorage(
InMemoryStore(configuration: configuration),
completion: { result in
switch result {
case .Success(let storage):
completion(PersistentStoreResult(self.persistentStoreForStorage(storage)!))
case .Failure(let error):
completion(PersistentStoreResult(error as NSError))
}
}
)
}
/**
Deprecated. Use `addStorage(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addStorage(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return self.addStorage(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
localStorageOptions: resetStoreOnModelMismatch ? .RecreateStoreOnModelMismatch : .None
),
completion: { result in
switch result {
case .Success(let storage):
completion(PersistentStoreResult(self.persistentStoreForStorage(storage)!))
case .Failure(let error):
completion(PersistentStoreResult(error as NSError))
}
}
)
}
/**
Deprecated. Use `addSQLiteStore(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addSQLiteStore(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func addSQLiteStore(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return self.addStorage(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
localStorageOptions: resetStoreOnModelMismatch ? .RecreateStoreOnModelMismatch : .None
),
completion: { result in
switch result {
case .Success(let storage):
completion(PersistentStoreResult(self.persistentStoreForStorage(storage)!))
case .Failure(let error):
completion(PersistentStoreResult(error as NSError))
}
}
)
}
/**
Deprecated. Use `upgradeStorageIfNeeded(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use upgradeStorageIfNeeded(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.upgradeStorageIfNeeded(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles
),
completion: completion
)
}
/**
Deprecated. Use `upgradeStorageIfNeeded(_:completion:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use upgradeStorageIfNeeded(_:completion:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.upgradeStorageIfNeeded(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles
),
completion: completion
)
}
/**
Deprecated. Use `requiredMigrationsForStorage(_:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use requiredMigrationsForStorage(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
@warn_unused_result
public func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
return try self.requiredMigrationsForStorage(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles
)
)
}
/**
Deprecated. Use `requiredMigrationsForStorage(_:)` by passing a `LegacySQLiteStore` instance.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use requiredMigrationsForStorage(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
@warn_unused_result
public func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
return try self.requiredMigrationsForStorage(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles
)
)
}
}
+9 -9
View File
@@ -87,9 +87,9 @@ 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.
*/
public init<T: CollectionType where T.Generator.Element == String, T.Index: BidirectionalIndexType>(_ elements: T) {
public init<T: Collection where T.Iterator.Element == String, T.SubSequence.Iterator.Element == String, T.Index: Comparable>(_ elements: T) {
CoreStore.assert(Set(elements).count == Array(elements).count, "\(cs_typeName(MigrationChain))'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.")
var lastVersion: String?
var versionTree = [String: String]()
@@ -105,8 +105,8 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
}
self.versionTree = versionTree
self.rootVersions = Set([elements.first].flatMap { $0 == nil ? [] : [$0!] })
self.leafVersions = Set([elements.last].flatMap { $0 == nil ? [] : [$0!] })
self.rootVersions = Set(elements.prefix(1))
self.leafVersions = Set(elements.suffix(1))
self.valid = valid
}
@@ -124,7 +124,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
return
}
CoreStore.assert(false, "\(cs_typeName(MigrationChain))'s migration chain could not be created due to ambiguous version paths.")
CoreStore.assert(false, "\(cs_typeName(MigrationChain.self))'s migration chain could not be created due to ambiguous version paths.")
valid = false
}
@@ -142,7 +142,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
if checklist.contains(nextVersion) {
CoreStore.assert(false, "\(cs_typeName(MigrationChain))'s migration chain could not be created due to looping version paths.")
CoreStore.assert(false, "\(cs_typeName(MigrationChain.self))'s migration chain could not be created due to looping version paths.")
return true
}
@@ -154,7 +154,7 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
}
self.versionTree = versionTree
self.rootVersions = Set(versionTree.keys).subtract(versionTree.values)
self.rootVersions = Set(versionTree.keys).subtracting(versionTree.values)
self.leafVersions = leafVersions
self.valid = valid && Set(versionTree.keys).union(versionTree.values).filter { isVersionAmbiguous($0) }.count <= 0
}
@@ -227,14 +227,14 @@ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, D
return self.versionTree.count <= 0
}
internal func contains(version: String) -> Bool {
internal func contains(_ version: String) -> Bool {
return self.rootVersions.contains(version)
|| self.leafVersions.contains(version)
|| self.versionTree[version] != nil
}
internal func nextVersionFrom(version: String) -> String? {
internal func nextVersionFrom(_ version: String) -> String? {
guard let nextVersion = self.versionTree[version] where nextVersion != version else {
+13 -13
View File
@@ -57,17 +57,17 @@ import Foundation
}
```
*/
public enum MigrationResult: BooleanType, Hashable {
public enum MigrationResult: Boolean, 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.
*/
case Success([MigrationType])
case success([MigrationType])
/**
`SaveResult.Failure` indicates that the migration failed. The associated object for this value is the a `CoreStoreError` enum value.
*/
case Failure(CoreStoreError)
case failure(CoreStoreError)
// MARK: BooleanType
@@ -76,8 +76,8 @@ public enum MigrationResult: BooleanType, Hashable {
switch self {
case .Success: return true
case .Failure: return false
case .success: return true
case .failure: return false
}
}
@@ -88,11 +88,11 @@ public enum MigrationResult: BooleanType, Hashable {
switch self {
case .Success(let migrationTypes):
case .success(let migrationTypes):
return self.boolValue.hashValue
^ migrationTypes.map { $0.hashValue }.reduce(0, combine: ^).hashValue
case .Failure(let error):
case .failure(let error):
return self.boolValue.hashValue ^ error.hashValue
}
}
@@ -102,17 +102,17 @@ public enum MigrationResult: BooleanType, Hashable {
internal init(_ migrationTypes: [MigrationType]) {
self = .Success(migrationTypes)
self = .success(migrationTypes)
}
internal init(_ error: CoreStoreError) {
self = .Failure(error)
self = .failure(error)
}
internal init(_ error: ErrorType) {
internal init(_ error: ErrorProtocol) {
self = .Failure(CoreStoreError(error))
self = .failure(CoreStoreError(error))
}
}
@@ -124,10 +124,10 @@ public func == (lhs: MigrationResult, rhs: MigrationResult) -> Bool {
switch (lhs, rhs) {
case (.Success(let migrationTypes1), .Success(let migrationTypes2)):
case (.success(let migrationTypes1), .success(let migrationTypes2)):
return migrationTypes1 == migrationTypes2
case (.Failure(let error1), .Failure(let error2)):
case (.failure(let error1), .failure(let error2)):
return error1 == error2
default:
+21 -21
View File
@@ -31,22 +31,22 @@ import Foundation
/**
The `MigrationType` specifies the type of migration required for a store.
*/
public enum MigrationType: BooleanType, Hashable {
public enum MigrationType: Boolean, Hashable {
/**
Indicates that the persistent store matches the latest model version and no migration is needed
*/
case None(version: String)
case none(version: String)
/**
Indicates that the persistent store does not match the latest model version but Core Data can infer the mapping model, so a lightweight migration is needed
*/
case Lightweight(sourceVersion: String, destinationVersion: String)
case lightweight(sourceVersion: String, destinationVersion: String)
/**
Indicates that the persistent store does not match the latest model version and Core Data could not infer a mapping model, so a custom migration is needed
*/
case Heavyweight(sourceVersion: String, destinationVersion: String)
case heavyweight(sourceVersion: String, destinationVersion: String)
/**
Returns the source model version for the migration type. If no migration is required, `sourceVersion` will be equal to the `destinationVersion`.
@@ -55,13 +55,13 @@ public enum MigrationType: BooleanType, Hashable {
switch self {
case .None(let version):
case .none(let version):
return version
case .Lightweight(let sourceVersion, _):
case .lightweight(let sourceVersion, _):
return sourceVersion
case .Heavyweight(let sourceVersion, _):
case .heavyweight(let sourceVersion, _):
return sourceVersion
}
}
@@ -73,13 +73,13 @@ public enum MigrationType: BooleanType, Hashable {
switch self {
case .None(let version):
case .none(let version):
return version
case .Lightweight(_, let destinationVersion):
case .lightweight(_, let destinationVersion):
return destinationVersion
case .Heavyweight(_, let destinationVersion):
case .heavyweight(_, let destinationVersion):
return destinationVersion
}
}
@@ -89,7 +89,7 @@ public enum MigrationType: BooleanType, Hashable {
*/
public var isLightweightMigration: Bool {
if case .Lightweight = self {
if case .lightweight = self {
return true
}
@@ -101,7 +101,7 @@ public enum MigrationType: BooleanType, Hashable {
*/
public var isHeavyweightMigration: Bool {
if case .Heavyweight = self {
if case .heavyweight = self {
return true
}
@@ -115,9 +115,9 @@ public enum MigrationType: BooleanType, Hashable {
switch self {
case .None: return false
case .Lightweight: return true
case .Heavyweight: return true
case .none: return false
case .lightweight: return true
case .heavyweight: return true
}
}
@@ -129,13 +129,13 @@ public enum MigrationType: BooleanType, Hashable {
let preHash = self.boolValue.hashValue ^ self.isHeavyweightMigration.hashValue
switch self {
case .None(let version):
case .none(let version):
return preHash ^ version.hashValue
case .Lightweight(let sourceVersion, let destinationVersion):
case .lightweight(let sourceVersion, let destinationVersion):
return preHash ^ sourceVersion.hashValue ^ destinationVersion.hashValue
case .Heavyweight(let sourceVersion, let destinationVersion):
case .heavyweight(let sourceVersion, let destinationVersion):
return preHash ^ sourceVersion.hashValue ^ destinationVersion.hashValue
}
}
@@ -149,13 +149,13 @@ public func == (lhs: MigrationType, rhs: MigrationType) -> Bool {
switch (lhs, rhs) {
case (.None(let version1), .None(let version2)):
case (.none(let version1), .none(let version2)):
return version1 == version2
case (.Lightweight(let source1, let destination1), .Lightweight(let source2, let destination2)):
case (.lightweight(let source1, let destination1), .lightweight(let source2, let destination2)):
return source1 == source2 && destination1 == destination2
case (.Heavyweight(let source1, let destination1), .Heavyweight(let source2, let destination2)):
case (.heavyweight(let source1, let destination1), .heavyweight(let source2, let destination2)):
return source1 == source2 && destination1 == destination2
default:
+21 -21
View File
@@ -60,17 +60,17 @@ import CoreData
)
```
*/
public enum SetupResult<T: StorageInterface>: BooleanType, Hashable {
public enum SetupResult<T: StorageInterface>: Boolean, Hashable {
/**
`SetupResult.Success` indicates that the storage setup succeeded. The associated object for this `enum` value is the related `StorageInterface` instance.
*/
case Success(T)
case success(T)
/**
`SetupResult.Failure` indicates that the storage setup failed. The associated object for this value is the related `CoreStoreError` enum value.
*/
case Failure(CoreStoreError)
case failure(CoreStoreError)
// MARK: BooleanType
@@ -79,8 +79,8 @@ public enum SetupResult<T: StorageInterface>: BooleanType, Hashable {
switch self {
case .Success: return true
case .Failure: return false
case .success: return true
case .failure: return false
}
}
@@ -91,10 +91,10 @@ public enum SetupResult<T: StorageInterface>: BooleanType, Hashable {
switch self {
case .Success(let storage):
case .success(let storage):
return self.boolValue.hashValue ^ ObjectIdentifier(storage).hashValue
case .Failure(let error):
case .failure(let error):
return self.boolValue.hashValue ^ error.hashValue
}
}
@@ -104,17 +104,17 @@ public enum SetupResult<T: StorageInterface>: BooleanType, Hashable {
internal init(_ storage: T) {
self = .Success(storage)
self = .success(storage)
}
internal init(_ error: CoreStoreError) {
self = .Failure(error)
self = .failure(error)
}
internal init(_ error: ErrorType) {
internal init(_ error: ErrorProtocol) {
self = .Failure(CoreStoreError(error))
self = .failure(CoreStoreError(error))
}
}
@@ -126,10 +126,10 @@ public func == <T: StorageInterface, U: StorageInterface>(lhs: SetupResult<T>, r
switch (lhs, rhs) {
case (.Success(let storage1), .Success(let storage2)):
case (.success(let storage1), .success(let storage2)):
return storage1 === storage2
case (.Failure(let error1), .Failure(let error2)):
case (.failure(let error1), .failure(let error2)):
return error1 == error2
default:
@@ -143,18 +143,18 @@ public func == <T: StorageInterface, U: StorageInterface>(lhs: SetupResult<T>, r
/**
Deprecated. Replaced by `SetupResult<T>` when using the new `addStorage(_:completion:)` method variants.
*/
@available(*, deprecated=2.0.0, message="Replaced by SetupResult by using the new addStorage(_:completion:) method variants.")
public enum PersistentStoreResult: BooleanType {
@available(*, deprecated: 2.0.0, message: "Replaced by SetupResult by using the new addStorage(_:completion:) method variants.")
public enum PersistentStoreResult: Boolean {
/**
Deprecated. Replaced by `SetupResult.Success` when using the new `addStorage(_:completion:)` method variants.
*/
case Success(NSPersistentStore)
case success(NSPersistentStore)
/**
Deprecated. Replaced by `SetupResult.Failure` when using the new `addStorage(_:completion:)` method variants.
*/
case Failure(NSError)
case failure(NSError)
// MARK: BooleanType
@@ -163,8 +163,8 @@ public enum PersistentStoreResult: BooleanType {
switch self {
case .Success: return true
case .Failure: return false
case .success: return true
case .failure: return false
}
}
@@ -173,11 +173,11 @@ public enum PersistentStoreResult: BooleanType {
internal init(_ store: NSPersistentStore) {
self = .Success(store)
self = .success(store)
}
internal init(_ error: NSError) {
self = .Failure(error)
self = .failure(error)
}
}
@@ -43,7 +43,7 @@ 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.
*/
@objc
public func commitWithCompletion(completion: ((result: CSSaveResult) -> Void)?) {
public func commitWithCompletion(_ completion: ((result: CSSaveResult) -> Void)?) {
self.bridgeToSwift.commit { (result) in
@@ -58,7 +58,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
- returns: a `CSSaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
@objc
public func beginSynchronous(closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge {
@@ -87,7 +87,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
@objc
public override func createInto(into: CSInto) -> AnyObject {
public override func createInto(_ into: CSInto) -> AnyObject {
return self.bridgeToSwift.create(into.bridgeToSwift)
}
@@ -100,7 +100,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public override func editObject(object: NSManagedObject?) -> AnyObject? {
public override func editObject(_ object: NSManagedObject?) -> AnyObject? {
return self.bridgeToSwift.edit(object)
}
@@ -114,7 +114,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public override func editInto(into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
public override func editInto(_ into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
return self.bridgeToSwift.edit(into.bridgeToSwift, objectID)
}
@@ -125,7 +125,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
- parameter object: the `NSManagedObject` type to be deleted
*/
@objc
public override func deleteObject(object: NSManagedObject?) {
public override func deleteObject(_ object: NSManagedObject?) {
self.bridgeToSwift.delete(object)
}
@@ -136,7 +136,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction {
- parameter objects: the `NSManagedObject`s type to be deleted
*/
@objc
public override func deleteObjects(objects: [NSManagedObject]) {
public override func deleteObjects(_ objects: [NSManagedObject]) {
self.bridgeToSwift.delete(objects)
}
@@ -39,11 +39,11 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchExistingObject(object: NSManagedObject) -> AnyObject? {
public func fetchExistingObject(_ object: NSManagedObject) -> AnyObject? {
do {
return try self.bridgeToSwift.context.existingObjectWithID(object.objectID)
return try self.bridgeToSwift.context.existingObject(with: object.objectID)
}
catch _ {
@@ -59,11 +59,11 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchExistingObjectWithID(objectID: NSManagedObjectID) -> AnyObject? {
public func fetchExistingObjectWithID(_ objectID: NSManagedObjectID) -> AnyObject? {
do {
return try self.bridgeToSwift.context.existingObjectWithID(objectID)
return try self.bridgeToSwift.context.existingObject(with: objectID)
}
catch _ {
@@ -79,9 +79,9 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchExistingObjects(objects: [NSManagedObject]) -> [AnyObject] {
public func fetchExistingObjects(_ objects: [NSManagedObject]) -> [AnyObject] {
return objects.flatMap { try? self.bridgeToSwift.context.existingObjectWithID($0.objectID) }
return objects.flatMap { try? self.bridgeToSwift.context.existingObject(with: $0.objectID) }
}
/**
@@ -92,9 +92,9 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchExistingObjectsWithIDs(objectIDs: [NSManagedObjectID]) -> [AnyObject] {
public func fetchExistingObjectsWithIDs(_ objectIDs: [NSManagedObjectID]) -> [AnyObject] {
return objectIDs.flatMap { try? self.bridgeToSwift.context.existingObjectWithID($0) }
return objectIDs.flatMap { try? self.bridgeToSwift.context.existingObject(with: $0) }
}
/**
@@ -106,7 +106,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchOneFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
public func fetchOneFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
@@ -124,7 +124,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchAllFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
public func fetchAllFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
@@ -142,7 +142,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchCountFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
public func fetchCountFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
@@ -160,7 +160,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func fetchObjectIDFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
public func fetchObjectIDFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
@@ -181,7 +181,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func queryValueFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
public func queryValueFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
@@ -202,7 +202,7 @@ public extension CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func queryAttributesFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
public func queryAttributesFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
CoreStore.assert(
self.bridgeToSwift.isRunningInAllowedQueue(),
+12 -12
View File
@@ -55,7 +55,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
@objc
public func createInto(into: CSInto) -> AnyObject {
public func createInto(_ into: CSInto) -> AnyObject {
return self.bridgeToSwift.create(into.bridgeToSwift)
}
@@ -68,7 +68,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func editObject(object: NSManagedObject?) -> AnyObject? {
public func editObject(_ object: NSManagedObject?) -> AnyObject? {
return self.bridgeToSwift.edit(object)
}
@@ -82,7 +82,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func editInto(into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
public func editInto(_ into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
return self.bridgeToSwift.edit(into.bridgeToSwift, objectID)
}
@@ -93,7 +93,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
- parameter object: the `NSManagedObject` to be deleted
*/
@objc
public func deleteObject(object: NSManagedObject?) {
public func deleteObject(_ object: NSManagedObject?) {
self.bridgeToSwift.delete(object)
}
@@ -104,7 +104,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
- parameter objects: the `NSManagedObject`s to be deleted
*/
@objc
public func deleteObjects(objects: [NSManagedObject]) {
public func deleteObjects(_ objects: [NSManagedObject]) {
self.bridgeToSwift.delete(objects)
}
@@ -141,7 +141,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func insertedObjectsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObject> {
public func insertedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.bridgeToSwift.insertedObjects(entity)
}
@@ -166,7 +166,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func insertedObjectIDsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
public func insertedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.bridgeToSwift.insertedObjectIDs(entity)
}
@@ -191,7 +191,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func updatedObjectsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObject> {
public func updatedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.bridgeToSwift.updatedObjects(entity)
}
@@ -216,7 +216,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func updatedObjectIDsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
public func updatedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.bridgeToSwift.updatedObjectIDs(entity)
}
@@ -241,7 +241,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func deletedObjectsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObject> {
public func deletedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.bridgeToSwift.deletedObjects(entity)
}
@@ -267,7 +267,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func deletedObjectIDsOfType(entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
public func deletedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.bridgeToSwift.deletedObjectIDs(entity)
}
@@ -280,7 +280,7 @@ public class CSBaseDataTransaction: NSObject, CoreStoreObjectiveCType {
return ObjectIdentifier(self.bridgeToSwift).hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSBaseDataTransaction else {
+3 -3
View File
@@ -38,7 +38,7 @@ import CoreData
public protocol CSFetchClause {
@objc
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>)
}
@@ -53,7 +53,7 @@ public protocol CSFetchClause {
public protocol CSQueryClause {
@objc
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>)
}
@@ -68,5 +68,5 @@ public protocol CSQueryClause {
public protocol CSDeleteClause {
@objc
func applyToFetchRequest(fetchRequest: NSFetchRequest)
func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>)
}
@@ -48,7 +48,7 @@ public extension CSCoreStore {
- parameter storage: the `CSInMemoryStore` instance
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `CSSetupResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a failure `CSSetupResult` result if an error occurs asynchronously.
*/
public static func addInMemoryStorage(storage: CSInMemoryStore, completion: (CSSetupResult) -> Void) {
public static func addInMemoryStorage(_ storage: CSInMemoryStore, completion: (CSSetupResult) -> Void) {
self.defaultStack.addInMemoryStorage(storage, completion: completion)
}
@@ -74,7 +74,7 @@ public extension CSCoreStore {
- parameter error: the `NSError` pointer that indicates the reason in case of an failure
- returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set.
*/
public static func addSQLiteStorage(storage: CSSQLiteStore, completion: (CSSetupResult) -> Void, error: NSErrorPointer) -> NSProgress? {
public static func addSQLiteStorage(_ storage: CSSQLiteStore, completion: (CSSetupResult) -> Void, error: NSErrorPointer) -> Progress? {
return self.defaultStack.addSQLiteStorage(storage, completion: completion, error: error)
}
@@ -88,7 +88,7 @@ public extension CSCoreStore {
- returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set.
*/
@objc
public static func upgradeStorageIfNeeded(storage: CSSQLiteStore, completion: (CSMigrationResult) -> Void, error: NSErrorPointer) -> NSProgress? {
public static func upgradeStorageIfNeeded(_ storage: CSSQLiteStore, completion: (CSMigrationResult) -> Void, error: NSErrorPointer) -> Progress? {
return self.defaultStack.upgradeStorageIfNeeded(storage, completion: completion, error: error)
}
@@ -102,7 +102,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func requiredMigrationsForSQLiteStore(storage: CSSQLiteStore, error: NSErrorPointer) -> [CSMigrationType]? {
public static func requiredMigrationsForSQLiteStore(_ storage: CSSQLiteStore, error: NSErrorPointer) -> [CSMigrationType]? {
return self.defaultStack.requiredMigrationsForSQLiteStore(storage, error: error)
}
@@ -41,7 +41,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func monitorObject(object: NSManagedObject) -> CSObjectMonitor {
public static func monitorObject(_ object: NSManagedObject) -> CSObjectMonitor {
return self.defaultStack.monitorObject(object)
}
@@ -55,7 +55,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func monitorListFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> CSListMonitor {
public static func monitorListFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> CSListMonitor {
return self.defaultStack.monitorListFrom(from, fetchClauses: fetchClauses)
}
@@ -68,7 +68,7 @@ public extension CSCoreStore {
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
@objc
public static func monitorListByCreatingAsynchronously(createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, fetchClauses: [CSFetchClause]) {
public static func monitorListByCreatingAsynchronously(_ createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, fetchClauses: [CSFetchClause]) {
return self.defaultStack.monitorListByCreatingAsynchronously(
createAsynchronously,
@@ -87,7 +87,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func monitorSectionedListFrom(from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) -> CSListMonitor {
public static func monitorSectionedListFrom(_ from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) -> CSListMonitor {
return self.defaultStack.monitorSectionedListFrom(
from,
@@ -105,7 +105,7 @@ public extension CSCoreStore {
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
@objc
public static func monitorSectionedListByCreatingAsynchronously(createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) {
public static func monitorSectionedListByCreatingAsynchronously(_ createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) {
self.defaultStack.monitorSectionedListByCreatingAsynchronously(
createAsynchronously,
+11 -11
View File
@@ -39,7 +39,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchExistingObject(object: NSManagedObject) -> AnyObject? {
public static func fetchExistingObject(_ object: NSManagedObject) -> AnyObject? {
return self.defaultStack.fetchExistingObject(object)
}
@@ -52,7 +52,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchExistingObjectWithID(objectID: NSManagedObjectID) -> AnyObject? {
public static func fetchExistingObjectWithID(_ objectID: NSManagedObjectID) -> AnyObject? {
return self.defaultStack.fetchExistingObjectWithID(objectID)
}
@@ -65,7 +65,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchExistingObjects(objects: [NSManagedObject]) -> [AnyObject] {
public static func fetchExistingObjects(_ objects: [NSManagedObject]) -> [AnyObject] {
return self.defaultStack.fetchExistingObjects(objects)
}
@@ -78,7 +78,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchExistingObjectsWithIDs(objectIDs: [NSManagedObjectID]) -> [AnyObject] {
public static func fetchExistingObjectsWithIDs(_ objectIDs: [NSManagedObjectID]) -> [AnyObject] {
return self.defaultStack.fetchExistingObjectsWithIDs(objectIDs)
}
@@ -92,7 +92,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchOneFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
public static func fetchOneFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
return self.defaultStack.fetchOneFrom(from, fetchClauses: fetchClauses)
}
@@ -106,7 +106,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchAllFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
public static func fetchAllFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
return self.defaultStack.fetchAllFrom(from, fetchClauses: fetchClauses)
}
@@ -120,7 +120,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchCountFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
public static func fetchCountFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
return self.defaultStack.fetchCountFrom(from, fetchClauses: fetchClauses)
}
@@ -134,7 +134,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchObjectIDFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
public static func fetchObjectIDFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
return self.defaultStack.fetchObjectIDFrom(from, fetchClauses: fetchClauses)
}
@@ -148,7 +148,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func fetchObjectIDsFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
public static func fetchObjectIDsFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
return self.defaultStack.fetchObjectIDsFrom(from, fetchClauses: fetchClauses)
}
@@ -165,7 +165,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func queryValueFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
public static func queryValueFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
return self.defaultStack.queryValueFrom(from, selectClause: selectClause, queryClauses: queryClauses)
}
@@ -182,7 +182,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func queryAttributesFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
public static func queryAttributesFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
return self.defaultStack.queryAttributesFrom(from, selectClause: selectClause, queryClauses: queryClauses)
}
+7 -7
View File
@@ -56,7 +56,7 @@ public extension CSCoreStore {
- returns: the `NSManagedObject` class for the given entity name, or `nil` if not found
*/
@objc
public static func entityClassWithName(name: String) -> NSManagedObject.Type? {
public static func entityClassWithName(_ name: String) -> NSManagedObject.Type? {
return CoreStore.entityTypesByName[name]
}
@@ -65,7 +65,7 @@ public extension CSCoreStore {
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from `defaultStack`'s model.
*/
@objc
public static func entityDescriptionForClass(type: NSManagedObject.Type) -> NSEntityDescription? {
public static func entityDescriptionForClass(_ type: NSManagedObject.Type) -> NSEntityDescription? {
return CoreStore.entityDescriptionForType(type)
}
@@ -80,7 +80,7 @@ public extension CSCoreStore {
- returns: the `CSInMemoryStore` added to the `defaultStack`
*/
@objc
public static func addInMemoryStorageAndWaitAndReturnError(error: NSErrorPointer) -> CSInMemoryStore? {
public static func addInMemoryStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSInMemoryStore? {
return self.defaultStack.addInMemoryStorageAndWaitAndReturnError(error)
}
@@ -95,7 +95,7 @@ public extension CSCoreStore {
- returns: the `CSSQLiteStore` added to the `defaultStack`
*/
@objc
public static func addSQLiteStorageAndWaitAndReturnError(error: NSErrorPointer) -> CSSQLiteStore? {
public static func addSQLiteStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSSQLiteStore? {
return self.defaultStack.addSQLiteStorageAndWaitAndReturnError(error)
}
@@ -114,7 +114,7 @@ public extension CSCoreStore {
- returns: the `CSInMemoryStore` added to the `defaultStack`
*/
@objc
public static func addInMemoryStorageAndWait(storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? {
public static func addInMemoryStorageAndWait(_ storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? {
return self.defaultStack.addInMemoryStorageAndWait(storage, error: error)
}
@@ -133,8 +133,8 @@ public extension CSCoreStore {
- returns: the `CSSQLiteStore` added to the `defaultStack`
*/
@objc
public static func addSQLiteStorageAndWait(storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? {
public static func addSQLiteStorageAndWait(_ storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? {
return self.defaultStack.addSQLiteStorageAndWait(storage, error: error)
}
}
}
@@ -36,7 +36,7 @@ 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`.
*/
@objc
public static func beginAsynchronous(closure: (transaction: CSAsynchronousDataTransaction) -> Void) {
public static func beginAsynchronous(_ closure: (transaction: CSAsynchronousDataTransaction) -> Void) {
return CoreStore.beginAsynchronous { (transaction) in
@@ -51,7 +51,7 @@ public extension CSCoreStore {
- returns: a `CSSaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
@objc
public static func beginSynchronous(closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
public static func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge {
@@ -86,7 +86,7 @@ public extension CSCoreStore {
*/
@objc
@warn_unused_result
public static func beginUnsafeWithSupportsUndo(supportsUndo: Bool) -> CSUnsafeDataTransaction {
public static func beginUnsafeWithSupportsUndo(_ supportsUndo: Bool) -> CSUnsafeDataTransaction {
return bridge {
@@ -49,7 +49,7 @@ public extension CSDataStack {
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `CSSetupResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a failure `CSSetupResult` result if an error occurs asynchronously.
*/
@objc
public func addInMemoryStorage(storage: CSInMemoryStore, completion: (CSSetupResult) -> Void) {
public func addInMemoryStorage(_ storage: CSInMemoryStore, completion: (CSSetupResult) -> Void) {
self.bridgeToSwift.addStorage(
storage.bridgeToSwift,
@@ -79,7 +79,7 @@ public extension CSDataStack {
- returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set.
*/
@objc
public func addSQLiteStorage(storage: CSSQLiteStore, completion: (CSSetupResult) -> Void, error: NSErrorPointer) -> NSProgress? {
public func addSQLiteStorage(_ storage: CSSQLiteStore, completion: (CSSetupResult) -> Void, error: NSErrorPointer) -> Progress? {
return bridge(error) {
@@ -99,7 +99,7 @@ public extension CSDataStack {
- returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set.
*/
@objc
public func upgradeStorageIfNeeded(storage: CSSQLiteStore, completion: (CSMigrationResult) -> Void, error: NSErrorPointer) -> NSProgress? {
public func upgradeStorageIfNeeded(_ storage: CSSQLiteStore, completion: (CSMigrationResult) -> Void, error: NSErrorPointer) -> Progress? {
return bridge(error) {
@@ -119,11 +119,11 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func requiredMigrationsForSQLiteStore(storage: CSSQLiteStore, error: NSErrorPointer) -> [CSMigrationType]? {
public func requiredMigrationsForSQLiteStore(_ storage: CSSQLiteStore, error: NSErrorPointer) -> [CSMigrationType]? {
return bridge(error) {
try self.bridgeToSwift.requiredMigrationsForStorage(storage.bridgeToSwift)
}
}
}
}
+13 -13
View File
@@ -41,7 +41,7 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func monitorObject(object: NSManagedObject) -> CSObjectMonitor {
public func monitorObject(_ object: NSManagedObject) -> CSObjectMonitor {
return bridge {
@@ -58,10 +58,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func monitorListFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> CSListMonitor {
public func monitorListFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> CSListMonitor {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
CoreStore.assert(
@@ -76,7 +76,7 @@ public extension CSDataStack {
sectionBy: nil,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest.cs_dynamicCast()) }
}
)
}
@@ -90,10 +90,10 @@ public extension CSDataStack {
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
@objc
public func monitorListByCreatingAsynchronously(createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, fetchClauses: [CSFetchClause]) {
public func monitorListByCreatingAsynchronously(_ createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, fetchClauses: [CSFetchClause]) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
CoreStore.assert(
@@ -106,7 +106,7 @@ public extension CSDataStack {
sectionBy: nil,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest.cs_dynamicCast()) }
},
createAsynchronously: {
@@ -125,10 +125,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func monitorSectionedListFrom(from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) -> CSListMonitor {
public func monitorSectionedListFrom(_ from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) -> CSListMonitor {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
CoreStore.assert(
@@ -143,7 +143,7 @@ public extension CSDataStack {
sectionBy: sectionBy.bridgeToSwift,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest.cs_dynamicCast()) }
}
)
}
@@ -157,10 +157,10 @@ public extension CSDataStack {
- parameter sectionBy: a `CSSectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
public func monitorSectionedListByCreatingAsynchronously(createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) {
public func monitorSectionedListByCreatingAsynchronously(_ createAsynchronously: (CSListMonitor) -> Void, from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
CoreStore.assert(
@@ -173,7 +173,7 @@ public extension CSDataStack {
sectionBy: sectionBy.bridgeToSwift,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest.cs_dynamicCast()) }
},
createAsynchronously: {
+22 -22
View File
@@ -39,11 +39,11 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchExistingObject(object: NSManagedObject) -> AnyObject? {
public func fetchExistingObject(_ object: NSManagedObject) -> AnyObject? {
do {
return try self.bridgeToSwift.mainContext.existingObjectWithID(object.objectID)
return try self.bridgeToSwift.mainContext.existingObject(with: object.objectID)
}
catch _ {
@@ -59,11 +59,11 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchExistingObjectWithID(objectID: NSManagedObjectID) -> AnyObject? {
public func fetchExistingObjectWithID(_ objectID: NSManagedObjectID) -> AnyObject? {
do {
return try self.bridgeToSwift.mainContext.existingObjectWithID(objectID)
return try self.bridgeToSwift.mainContext.existingObject(with: objectID)
}
catch _ {
@@ -79,9 +79,9 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchExistingObjects(objects: [NSManagedObject]) -> [AnyObject] {
public func fetchExistingObjects(_ objects: [NSManagedObject]) -> [AnyObject] {
return objects.flatMap { try? self.bridgeToSwift.mainContext.existingObjectWithID($0.objectID) }
return objects.flatMap { try? self.bridgeToSwift.mainContext.existingObject(with: $0.objectID) }
}
/**
@@ -92,9 +92,9 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchExistingObjectsWithIDs(objectIDs: [NSManagedObjectID]) -> [AnyObject] {
public func fetchExistingObjectsWithIDs(_ objectIDs: [NSManagedObjectID]) -> [AnyObject] {
return objectIDs.flatMap { try? self.bridgeToSwift.mainContext.existingObjectWithID($0) }
return objectIDs.flatMap { try? self.bridgeToSwift.mainContext.existingObject(with: $0) }
}
/**
@@ -106,10 +106,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchOneFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
public func fetchOneFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> AnyObject? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.fetchOne(from, fetchClauses)
@@ -124,10 +124,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchAllFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
public func fetchAllFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [AnyObject]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.fetchAll(from, fetchClauses)
@@ -142,10 +142,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchCountFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
public func fetchCountFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.fetchCount(from, fetchClauses)
@@ -160,10 +160,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchObjectIDFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
public func fetchObjectIDFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.fetchObjectID(from, fetchClauses)
@@ -178,10 +178,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func fetchObjectIDsFrom(from: CSFrom, fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
public func fetchObjectIDsFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to fetch from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.fetchObjectIDs(from, fetchClauses)
@@ -199,10 +199,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func queryValueFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
public func queryValueFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> AnyObject? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.queryValue(from, selectClause, queryClauses)
@@ -220,10 +220,10 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func queryAttributesFrom(from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
public func queryAttributesFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to query from a \(cs_typeName(self)) outside the main thread."
)
return self.bridgeToSwift.mainContext.queryAttributes(from, selectClause, queryClauses)
@@ -36,7 +36,7 @@ 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`.
*/
@objc
public func beginAsynchronous(closure: (transaction: CSAsynchronousDataTransaction) -> Void) {
public func beginAsynchronous(_ closure: (transaction: CSAsynchronousDataTransaction) -> Void) {
return self.bridgeToSwift.beginAsynchronous { (transaction) in
@@ -51,7 +51,7 @@ public extension CSDataStack {
- returns: a `CSSaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
@objc
public func beginSynchronous(closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge {
@@ -86,7 +86,7 @@ public extension CSDataStack {
*/
@objc
@warn_unused_result
public func beginUnsafeWithSupportsUndo(supportsUndo: Bool) -> CSUnsafeDataTransaction {
public func beginUnsafeWithSupportsUndo(_ supportsUndo: Bool) -> CSUnsafeDataTransaction {
return bridge {
+13 -13
View File
@@ -54,12 +54,12 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- parameter versionChain: the version strings that indicate the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
*/
@objc
public convenience init(modelName: String?, bundle: NSBundle?, versionChain: [String]?) {
public convenience init(modelName: String?, bundle: Bundle?, versionChain: [String]?) {
self.init(
DataStack(
modelName: modelName ?? DataStack.applicationName,
bundle: bundle ?? NSBundle.mainBundle(),
bundle: bundle ?? Bundle.main,
migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil
)
)
@@ -73,12 +73,12 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- parameter versionTree: the version strings that indicate the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
*/
@objc
public convenience init(modelName: String?, bundle: NSBundle?, versionTree: [String: String]?) {
public convenience init(modelName: String?, bundle: Bundle?, versionTree: [String: String]?) {
self.init(
DataStack(
modelName: modelName ?? DataStack.applicationName,
bundle: bundle ?? NSBundle.mainBundle(),
bundle: bundle ?? Bundle.main,
migrationChain: versionTree.flatMap { MigrationChain($0) } ?? nil
)
)
@@ -142,7 +142,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` class for the given entity name, or `nil` if not found
*/
@objc
public func entityClassWithName(name: String) -> NSManagedObject.Type? {
public func entityClassWithName(_ name: String) -> NSManagedObject.Type? {
return self.bridgeToSwift.entityTypesByName[name]
}
@@ -151,7 +151,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from stack's model.
*/
@objc
public func entityDescriptionForClass(type: NSManagedObject.Type) -> NSEntityDescription? {
public func entityDescriptionForClass(_ type: NSManagedObject.Type) -> NSEntityDescription? {
return self.bridgeToSwift.entityDescriptionForType(type)
}
@@ -166,11 +166,11 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- returns: the `CSInMemoryStore` added to the stack
*/
@objc
public func addInMemoryStorageAndWaitAndReturnError(error: NSErrorPointer) -> CSInMemoryStore? {
public func addInMemoryStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSInMemoryStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(InMemoryStore)
try self.bridgeToSwift.addStorageAndWait(InMemoryStore.self)
}
}
@@ -184,11 +184,11 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- returns: the `CSSQLiteStore` added to the stack
*/
@objc
public func addSQLiteStorageAndWaitAndReturnError(error: NSErrorPointer) -> CSSQLiteStore? {
public func addSQLiteStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSSQLiteStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(SQLiteStore)
try self.bridgeToSwift.addStorageAndWait(SQLiteStore.self)
}
}
@@ -206,7 +206,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- returns: the `CSInMemoryStore` added to the stack
*/
@objc
public func addInMemoryStorageAndWait(storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? {
public func addInMemoryStorageAndWait(_ storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? {
return bridge(error) {
@@ -228,7 +228,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
- returns: the `CSSQLiteStore` added to the stack
*/
@objc
public func addSQLiteStorageAndWait(storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? {
public func addSQLiteStorageAndWait(_ storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? {
return bridge(error) {
@@ -244,7 +244,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
return ObjectIdentifier(self.bridgeToSwift).hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSDataStack else {
+38 -38
View File
@@ -53,7 +53,7 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSError else {
@@ -77,53 +77,53 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
return swift
}
func createSwiftObject(error: CSError) -> CoreStoreError {
func createSwiftObject(_ error: CSError) -> CoreStoreError {
guard error.domain == CoreStoreErrorDomain else {
return .InternalError(NSError: self)
return .internalError(NSError: self)
}
guard let code = CoreStoreErrorCode(rawValue: error.code) else {
return .Unknown
return .unknown
}
let info = error.userInfo
switch code {
case .UnknownError:
return .Unknown
case .unknownError:
return .unknown
case .DifferentPersistentStoreExistsAtURL:
guard case let existingPersistentStoreURL as NSURL = info["existingPersistentStoreURL"] else {
case .differentPersistentStoreExistsAtURL:
guard case let existingPersistentStoreURL as URL = info["existingPersistentStoreURL"] else {
return .Unknown
return .unknown
}
return .DifferentStorageExistsAtURL(existingPersistentStoreURL: existingPersistentStoreURL)
return .differentStorageExistsAtURL(existingPersistentStoreURL: existingPersistentStoreURL)
case .MappingModelNotFound:
guard let localStoreURL = info["localStoreURL"] as? NSURL,
case .mappingModelNotFound:
guard let localStoreURL = info["localStoreURL"] as? URL,
let targetModel = info["targetModel"] as? NSManagedObjectModel,
let targetModelVersion = info["targetModelVersion"] as? String else {
return .Unknown
return .unknown
}
return .MappingModelNotFound(localStoreURL: localStoreURL, targetModel: targetModel, targetModelVersion: targetModelVersion)
return .mappingModelNotFound(localStoreURL: localStoreURL, targetModel: targetModel, targetModelVersion: targetModelVersion)
case .ProgressiveMigrationRequired:
guard let localStoreURL = info["localStoreURL"] as? NSURL else {
case .progressiveMigrationRequired:
guard let localStoreURL = info["localStoreURL"] as? URL else {
return .Unknown
return .unknown
}
return .ProgressiveMigrationRequired(localStoreURL: localStoreURL)
return .progressiveMigrationRequired(localStoreURL: localStoreURL)
case .InternalError:
case .internalError:
guard case let NSError as NSError = info["NSError"] else {
return .Unknown
return .unknown
}
return .InternalError(NSError: NSError)
return .internalError(NSError: NSError)
}
}
@@ -143,32 +143,32 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
let info: [NSObject: AnyObject]
switch swiftValue {
case .Unknown:
code = .UnknownError
case .unknown:
code = .unknownError
info = [:]
case .DifferentStorageExistsAtURL(let existingPersistentStoreURL):
code = .DifferentPersistentStoreExistsAtURL
case .differentStorageExistsAtURL(let existingPersistentStoreURL):
code = .differentPersistentStoreExistsAtURL
info = [
"existingPersistentStoreURL": existingPersistentStoreURL
]
case .MappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
code = .MappingModelNotFound
case .mappingModelNotFound(let localStoreURL, let targetModel, let targetModelVersion):
code = .mappingModelNotFound
info = [
"localStoreURL": localStoreURL,
"targetModel": targetModel,
"targetModelVersion": targetModelVersion
]
case .ProgressiveMigrationRequired(let localStoreURL):
code = .ProgressiveMigrationRequired
case .progressiveMigrationRequired(let localStoreURL):
code = .progressiveMigrationRequired
info = [
"localStoreURL": localStoreURL
]
case .InternalError(let NSError):
code = .InternalError
case .internalError(let NSError):
code = .internalError
info = [
"NSError": NSError
]
@@ -203,27 +203,27 @@ public enum CSErrorCode: Int {
/**
A failure occured because of an unknown error.
*/
case UnknownError
case unknownError
/**
The `NSPersistentStore` could note be initialized because another store existed at the specified `NSURL`.
*/
case DifferentPersistentStoreExistsAtURL
case differentPersistentStoreExistsAtURL
/**
An `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case MappingModelNotFound
case mappingModelNotFound
/**
Progressive migrations are disabled for a store, but an `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case ProgressiveMigrationRequired
case progressiveMigrationRequired
/**
An internal SDK call failed with the specified "NSError" userInfo key.
*/
case InternalError
case internalError
}
@@ -242,7 +242,7 @@ extension CoreStoreError: CoreStoreSwiftType {
// MARK: Internal
internal extension ErrorType {
internal extension ErrorProtocol {
internal var bridgeToSwift: CoreStoreError {
@@ -250,7 +250,7 @@ internal extension ErrorType {
case let error as CoreStoreError: return error
case let error as CSError: return error.bridgeToSwift
default: return .Unknown
default: return .unknown
}
}
+2 -2
View File
@@ -76,7 +76,7 @@ public final class CSGroupBy: NSObject, CSQueryClause, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSGroupBy else {
@@ -94,7 +94,7 @@ public final class CSGroupBy: NSObject, CSQueryClause, CoreStoreObjectiveCType {
// MARK: CSQueryClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
+1 -1
View File
@@ -92,7 +92,7 @@ public final class CSInMemoryStore: NSObject, CSStorageInterface, CoreStoreObjec
return ObjectIdentifier(self.bridgeToSwift).hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSInMemoryStore else {
+1 -1
View File
@@ -95,7 +95,7 @@ public final class CSInto: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSInto else {
+20 -20
View File
@@ -60,7 +60,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` at the specified index, or `nil` if out of bounds
*/
@objc
public func objectAtSafeIndex(index: Int) -> AnyObject? {
public func objectAtSafeIndex(_ index: Int) -> AnyObject? {
return self.bridgeToSwift[safeIndex: index]
}
@@ -73,7 +73,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` at the specified section and item index
*/
@objc
public func objectAtSectionIndex(sectionIndex: Int, itemIndex: Int) -> AnyObject {
public func objectAtSectionIndex(_ sectionIndex: Int, itemIndex: Int) -> AnyObject {
return self.bridgeToSwift[sectionIndex, itemIndex]
}
@@ -86,7 +86,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` at the specified section and item index, or `nil` if out of bounds
*/
@objc
public func objectAtSafeSectionIndex(sectionIndex: Int, safeItemIndex itemIndex: Int) -> AnyObject? {
public func objectAtSafeSectionIndex(_ sectionIndex: Int, safeItemIndex itemIndex: Int) -> AnyObject? {
return self.bridgeToSwift[safeSectionIndex: sectionIndex, safeItemIndex: itemIndex]
}
@@ -98,7 +98,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` at the specified index path
*/
@objc
public func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject {
public func objectAtIndexPath(_ indexPath: IndexPath) -> AnyObject {
return self.bridgeToSwift[indexPath]
}
@@ -110,7 +110,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- returns: the `NSManagedObject` at the specified index path, or `nil` if out of bounds
*/
@objc
public func objectAtSafeIndexPath(indexPath: NSIndexPath) -> AnyObject? {
public func objectAtSafeIndexPath(_ indexPath: IndexPath) -> AnyObject? {
return self.bridgeToSwift[safeIndexPath: indexPath]
}
@@ -135,7 +135,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func hasObjectsInSection(section: Int) -> Bool {
public func hasObjectsInSection(_ section: Int) -> Bool {
return self.bridgeToSwift.hasObjectsInSection(section)
}
@@ -160,7 +160,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func objectsInSection(section: Int) -> [NSManagedObject] {
public func objectsInSection(_ section: Int) -> [NSManagedObject] {
return self.bridgeToSwift.objectsInSection(section)
}
@@ -210,7 +210,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func numberOfObjectsInSection(section: Int) -> Int {
public func numberOfObjectsInSection(_ section: Int) -> Int {
return self.bridgeToSwift.numberOfObjectsInSection(section)
}
@@ -236,7 +236,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo {
public func sectionInfoAtIndex(_ section: Int) -> NSFetchedResultsSectionInfo {
return self.bridgeToSwift.sectionInfoAtIndex(section)
}
@@ -275,7 +275,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func targetSectionForSectionIndexTitle(title title: String, index: Int) -> Int {
public func targetSectionForSectionIndexTitle(title: String, index: Int) -> Int {
return self.bridgeToSwift.targetSectionForSectionIndex(title: title, index: index)
}
@@ -300,7 +300,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func indexOf(object: NSManagedObject) -> NSNumber? {
public func indexOf(_ object: NSManagedObject) -> NSNumber? {
return self.bridgeToSwift.indexOf(object)
}
@@ -313,7 +313,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
*/
@objc
@warn_unused_result
public func indexPathOf(object: NSManagedObject) -> NSIndexPath? {
public func indexPathOf(_ object: NSManagedObject) -> IndexPath? {
return self.bridgeToSwift.indexPathOf(object)
}
@@ -333,7 +333,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: a `CSListObserver` to send change notifications to
*/
@objc
public func addListObserver(observer: CSListObserver) {
public func addListObserver(_ observer: CSListObserver) {
let swift = self.bridgeToSwift
swift.unregisterObserver(observer)
@@ -369,7 +369,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: a `CSListObjectObserver` to send change notifications to
*/
public func addListObjectObserver(observer: CSListObjectObserver) {
public func addListObjectObserver(_ observer: CSListObjectObserver) {
let swift = self.bridgeToSwift
swift.unregisterObserver(observer)
@@ -425,7 +425,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: a `CSListSectionObserver` to send change notifications to
*/
@objc
public func addListSectionObserver(observer: CSListSectionObserver) {
public func addListSectionObserver(_ observer: CSListSectionObserver) {
let swift = self.bridgeToSwift
swift.unregisterObserver(observer)
@@ -488,7 +488,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: a `CSListObserver` to unregister notifications to
*/
@objc
public func removeListObserver(observer: CSListObserver) {
public func removeListObserver(_ observer: CSListObserver) {
self.bridgeToSwift.unregisterObserver(observer)
}
@@ -513,11 +513,11 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values.
*/
@objc
public func refetch(fetchClauses: [CSFetchClause]) {
public func refetch(_ fetchClauses: [CSFetchClause]) {
self.bridgeToSwift.refetch { (fetchRequest) in
self.bridgeToSwift.refetch { (fetchRequest: NSFetchRequest<NSManagedObject>) in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest.cs_dynamicCast()) }
}
}
@@ -529,7 +529,7 @@ public final class CSListMonitor: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSListMonitor else {
+10 -10
View File
@@ -51,7 +51,7 @@ public protocol CSListObserver: class, AnyObject {
- parameter monitor: the `CSListMonitor` monitoring the list being observed
*/
@objc
optional func listMonitorWillChange(monitor: CSListMonitor)
optional func listMonitorWillChange(_ monitor: CSListMonitor)
/**
Handles processing right after a change to the observed list occurs
@@ -59,7 +59,7 @@ public protocol CSListObserver: class, AnyObject {
- parameter monitor: the `CSListMonitor` monitoring the object being observed
*/
@objc
optional func listMonitorDidChange(monitor: CSListMonitor)
optional func listMonitorDidChange(_ monitor: CSListMonitor)
/**
This method is broadcast from within the `CSListMonitor`'s `-refetchWithFetchClauses:` method to let observers prepare for the internal `NSFetchedResultsController`'s pending change to its predicate, sort descriptors, etc. Note that the actual refetch will happen after the `NSFetchedResultsController`'s last `-controllerDidChangeContent:` notification completes.
@@ -67,7 +67,7 @@ public protocol CSListObserver: class, AnyObject {
- parameter monitor: the `CSListMonitor` monitoring the object being observed
*/
@objc
optional func listMonitorWillRefetch(monitor: CSListMonitor)
optional func listMonitorWillRefetch(_ monitor: CSListMonitor)
/**
After the `CSListMonitor`'s `-refetchWithFetchClauses:` method is called, this method is broadcast after the `NSFetchedResultsController`'s last `-controllerDidChangeContent:` notification completes.
@@ -75,7 +75,7 @@ public protocol CSListObserver: class, AnyObject {
- parameter monitor: the `CSListMonitor` monitoring the object being observed
*/
@objc
optional func listMonitorDidRefetch(monitor: CSListMonitor)
optional func listMonitorDidRefetch(_ monitor: CSListMonitor)
}
@@ -103,7 +103,7 @@ public protocol CSListObjectObserver: CSListObserver {
- parameter indexPath: the new `NSIndexPath` for the inserted object
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didInsertObject object: AnyObject, toIndexPath indexPath: NSIndexPath)
optional func listMonitor(_ monitor: CSListMonitor, didInsertObject object: AnyObject, toIndexPath indexPath: IndexPath)
/**
Notifies that an object was deleted from the specified `NSIndexPath` in the list
@@ -113,7 +113,7 @@ public protocol CSListObjectObserver: CSListObserver {
- parameter indexPath: the `NSIndexPath` for the deleted object
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didDeleteObject object: AnyObject, fromIndexPath indexPath: NSIndexPath)
optional func listMonitor(_ monitor: CSListMonitor, didDeleteObject object: AnyObject, fromIndexPath indexPath: IndexPath)
/**
Notifies that an object at the specified `NSIndexPath` was updated
@@ -123,7 +123,7 @@ public protocol CSListObjectObserver: CSListObserver {
- parameter indexPath: the `NSIndexPath` for the updated object
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didUpdateObject object: AnyObject, atIndexPath indexPath: NSIndexPath)
optional func listMonitor(_ monitor: CSListMonitor, didUpdateObject object: AnyObject, atIndexPath indexPath: IndexPath)
/**
Notifies that an object's index changed
@@ -134,7 +134,7 @@ public protocol CSListObjectObserver: CSListObserver {
- parameter toIndexPath: the new `NSIndexPath` for the moved object
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didMoveObject object: AnyObject, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath)
optional func listMonitor(_ monitor: CSListMonitor, didMoveObject object: AnyObject, fromIndexPath: IndexPath, toIndexPath: IndexPath)
}
@@ -163,7 +163,7 @@ public protocol CSListSectionObserver: CSListObjectObserver {
- parameter sectionIndex: the new section index for the new section
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
optional func listMonitor(_ monitor: CSListMonitor, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
/**
Notifies that a section was inserted at the specified index
@@ -173,7 +173,7 @@ public protocol CSListSectionObserver: CSListObjectObserver {
- parameter sectionIndex: the previous section index for the deleted section
*/
@objc
optional func listMonitor(monitor: CSListMonitor, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)
optional func listMonitor(_ monitor: CSListMonitor, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)
}
#endif
+10 -10
View File
@@ -61,7 +61,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
@objc
public var migrationTypes: [CSMigrationType]? {
guard case .Success(let migrationTypes) = self.bridgeToSwift else {
guard case .success(let migrationTypes) = self.bridgeToSwift else {
return nil
}
@@ -74,7 +74,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
@objc
public var error: NSError? {
guard case .Failure(let error) = self.bridgeToSwift else {
guard case .failure(let error) = self.bridgeToSwift else {
return nil
}
@@ -90,14 +90,14 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (migrationTypes: [CSMigrationType]) -> Void, @noescape failure: (error: NSError) -> Void) {
public func handleSuccess(@noescape _ success: (migrationTypes: [CSMigrationType]) -> Void, @noescape failure: (error: NSError) -> Void) {
switch self.bridgeToSwift {
case .Success(let migrationTypes):
case .success(let migrationTypes):
success(migrationTypes: migrationTypes.map { $0.bridgeToObjectiveC })
case .Failure(let error):
case .failure(let error):
failure(error: error.bridgeToObjectiveC)
}
}
@@ -110,9 +110,9 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (migrationTypes: [CSMigrationType]) -> Void) {
public func handleSuccess(@noescape _ success: (migrationTypes: [CSMigrationType]) -> Void) {
guard case .Success(let migrationTypes) = self.bridgeToSwift else {
guard case .success(let migrationTypes) = self.bridgeToSwift else {
return
}
@@ -127,9 +127,9 @@ 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.
*/
@objc
public func handleFailure(@noescape failure: (error: NSError) -> Void) {
public func handleFailure(@noescape _ failure: (error: NSError) -> Void) {
guard case .Failure(let error) = self.bridgeToSwift else {
guard case .failure(let error) = self.bridgeToSwift else {
return
}
@@ -144,7 +144,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSMigrationResult else {
+1 -1
View File
@@ -90,7 +90,7 @@ public final class CSMigrationType: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSMigrationType else {
+3 -3
View File
@@ -66,7 +66,7 @@ public final class CSObjectMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: an `CSObjectObserver` to send change notifications to
*/
public func addObjectObserver(observer: CSObjectObserver) {
public func addObjectObserver(_ observer: CSObjectObserver) {
let swift = self.bridgeToSwift
swift.unregisterObserver(observer)
@@ -94,7 +94,7 @@ public final class CSObjectMonitor: NSObject, CoreStoreObjectiveCType {
- parameter observer: an `CSObjectObserver` to unregister notifications to
*/
public func removeObjectObserver(observer: CSObjectObserver) {
public func removeObjectObserver(_ observer: CSObjectObserver) {
self.bridgeToSwift.unregisterObserver(observer)
}
@@ -107,7 +107,7 @@ public final class CSObjectMonitor: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSObjectMonitor else {
+3 -3
View File
@@ -50,7 +50,7 @@ public protocol CSObjectObserver: class, AnyObject {
- parameter object: the `NSManagedObject` instance being observed
*/
@objc
optional func objectMonitor(monitor: CSObjectMonitor, willUpdateObject object: AnyObject)
optional func objectMonitor(_ monitor: CSObjectMonitor, willUpdateObject object: AnyObject)
/**
Handles processing right after a change to the observed `object` occurs
@@ -60,7 +60,7 @@ public protocol CSObjectObserver: class, AnyObject {
- parameter changedPersistentKeys: an `NSSet` of key paths for the attributes that were changed. Note that `changedPersistentKeys` only contains keys for attributes/relationships present in the persistent store, thus transient properties will not be reported.
*/
@objc
optional func objectMonitor(monitor: CSObjectMonitor, didUpdateObject object: AnyObject, changedPersistentKeys: Set<String>)
optional func objectMonitor(_ monitor: CSObjectMonitor, didUpdateObject object: AnyObject, changedPersistentKeys: Set<String>)
/**
Handles processing right after `object` is deleted
@@ -69,7 +69,7 @@ public protocol CSObjectObserver: class, AnyObject {
- parameter object: the `NSManagedObject` instance being observed
*/
@objc
optional func objectMonitor(monitor: CSObjectMonitor, didDeleteObject object: AnyObject)
optional func objectMonitor(_ monitor: CSObjectMonitor, didDeleteObject object: AnyObject)
}
#endif
+5 -5
View File
@@ -41,7 +41,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
The list of sort descriptors
*/
@objc
public var sortDescriptors: [NSSortDescriptor] {
public var sortDescriptors: [SortDescriptor] {
return self.bridgeToSwift.sortDescriptors
}
@@ -57,7 +57,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
- parameter sortDescriptor: a `NSSortDescriptor`
*/
@objc
public convenience init(sortDescriptor: NSSortDescriptor) {
public convenience init(sortDescriptor: SortDescriptor) {
self.init(OrderBy(sortDescriptor))
}
@@ -73,7 +73,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
- parameter sortDescriptors: an array of `NSSortDescriptor`s
*/
@objc
public convenience init(sortDescriptors: [NSSortDescriptor]) {
public convenience init(sortDescriptors: [SortDescriptor]) {
self.init(OrderBy(sortDescriptors))
}
@@ -86,7 +86,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSOrderBy else {
@@ -104,7 +104,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
// MARK: CSFetchClause, CSQueryClause, CSDeleteClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
+9 -9
View File
@@ -46,13 +46,13 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
- parameter localStorageOptions: When the `CSSQLiteStore` is passed to the `CSDataStack`'s `addStorage()` methods, tells the `CSDataStack` how to setup the persistent store. Defaults to `CSLocalStorageOptionsNone`.
*/
@objc
public convenience init(fileURL: NSURL, configuration: String?, mappingModelBundles: [NSBundle]?, localStorageOptions: Int) {
public convenience init(fileURL: URL, configuration: String?, mappingModelBundles: [Bundle]?, localStorageOptions: Int) {
self.init(
SQLiteStore(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
mappingModelBundles: mappingModelBundles ?? Bundle.allBundles,
localStorageOptions: LocalStorageOptions(rawValue: localStorageOptions)
)
)
@@ -68,13 +68,13 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
- parameter localStorageOptions: When the `CSSQLiteStore` is passed to the `CSDataStack`'s `addStorage()` methods, tells the `CSDataStack` how to setup the persistent store. Defaults to `[CSLocalStorageOptions none]`.
*/
@objc
public convenience init(fileName: String, configuration: String?, mappingModelBundles: [NSBundle]?, localStorageOptions: Int) {
public convenience init(fileName: String, configuration: String?, mappingModelBundles: [Bundle]?, localStorageOptions: Int) {
self.init(
SQLiteStore(
fileName: fileName,
configuration: configuration,
mappingModelBundles: mappingModelBundles ?? NSBundle.allBundles(),
mappingModelBundles: mappingModelBundles ?? Bundle.allBundles,
localStorageOptions: LocalStorageOptions(rawValue: localStorageOptions)
)
)
@@ -98,16 +98,16 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
The `NSURL` that points to the SQLite file
*/
@objc
public var fileURL: NSURL {
public var fileURL: URL {
return self.bridgeToSwift.fileURL
return self.bridgeToSwift.fileURL as URL
}
/**
The `NSBundle`s from which to search mapping models for migrations
*/
@objc
public var mappingModelBundles: [NSBundle] {
public var mappingModelBundles: [Bundle] {
return self.bridgeToSwift.mappingModelBundles
}
@@ -154,7 +154,7 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
Called by the `CSDataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `CSSQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
@objc
public func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel, error: NSErrorPointer) -> Bool {
public func eraseStorageAndWait(soureModel: NSManagedObjectModel, error: NSErrorPointer) -> Bool {
return bridge(error) {
@@ -170,7 +170,7 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
return ObjectIdentifier(self.bridgeToSwift).hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSSQLiteStore else {
+10 -10
View File
@@ -61,7 +61,7 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
@objc
public var hasChanges: Bool {
guard case .Success(let hasChanges) = self.bridgeToSwift else {
guard case .success(let hasChanges) = self.bridgeToSwift else {
return false
}
@@ -74,7 +74,7 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
@objc
public var error: NSError? {
guard case .Failure(let error) = self.bridgeToSwift else {
guard case .failure(let error) = self.bridgeToSwift else {
return nil
}
@@ -90,14 +90,14 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (hasChanges: Bool) -> Void, @noescape failure: (error: NSError) -> Void) {
public func handleSuccess(@noescape _ success: (hasChanges: Bool) -> Void, @noescape failure: (error: NSError) -> Void) {
switch self.bridgeToSwift {
case .Success(let hasChanges):
case .success(let hasChanges):
success(hasChanges: hasChanges)
case .Failure(let error):
case .failure(let error):
failure(error: error.bridgeToObjectiveC)
}
}
@@ -110,9 +110,9 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (hasChanges: Bool) -> Void) {
public func handleSuccess(@noescape _ success: (hasChanges: Bool) -> Void) {
guard case .Success(let hasChanges) = self.bridgeToSwift else {
guard case .success(let hasChanges) = self.bridgeToSwift else {
return
}
@@ -127,9 +127,9 @@ 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.
*/
@objc
public func handleFailure(@noescape failure: (error: NSError) -> Void) {
public func handleFailure(@noescape _ failure: (error: NSError) -> Void) {
guard case .Failure(let error) = self.bridgeToSwift else {
guard case .failure(let error) = self.bridgeToSwift else {
return
}
@@ -144,7 +144,7 @@ public final class CSSaveResult: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSSaveResult else {
+2 -2
View File
@@ -46,7 +46,7 @@ public final class CSSectionBy: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSectionBy` clause with the key path to use to group `CSListMonitor` objects into sections
*/
@objc
public static func keyPath(sectionKeyPath: KeyPath) -> CSSectionBy {
public static func keyPath(_ sectionKeyPath: KeyPath) -> CSSectionBy {
return self.init(SectionBy(sectionKeyPath))
}
@@ -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
*/
@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))
}
+21 -21
View File
@@ -51,7 +51,7 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
@objc
public convenience init(keyPath: KeyPath) {
self.init(.Attribute(keyPath))
self.init(.attribute(keyPath))
}
/**
@@ -67,9 +67,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the average value of an attribute
*/
@objc
public static func average(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
public static func average(_ keyPath: KeyPath, as alias: KeyPath?) -> CSSelectTerm {
return self.init(.Average(keyPath, As: alias))
return self.init(.average(keyPath, As: alias))
}
/**
@@ -85,9 +85,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
@objc
public static func count(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
public static func count(_ keyPath: KeyPath, as alias: KeyPath?) -> CSSelectTerm {
return self.init(.Count(keyPath, As: alias))
return self.init(.count(keyPath, As: alias))
}
/**
@@ -103,9 +103,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the maximum value for an attribute
*/
@objc
public static func maximum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
public static func maximum(_ keyPath: KeyPath, as alias: KeyPath?) -> CSSelectTerm {
return self.init(.Maximum(keyPath, As: alias))
return self.init(.maximum(keyPath, As: alias))
}
/**
@@ -121,9 +121,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the minimum value for an attribute
*/
@objc
public static func minimum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
public static func minimum(_ keyPath: KeyPath, as alias: KeyPath?) -> CSSelectTerm {
return self.init(.Minimum(keyPath, As: alias))
return self.init(.minimum(keyPath, As: alias))
}
/**
@@ -139,9 +139,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the sum value for an attribute
*/
@objc
public static func sum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
public static func sum(_ keyPath: KeyPath, as alias: KeyPath?) -> CSSelectTerm {
return self.init(.Sum(keyPath, As: alias))
return self.init(.sum(keyPath, As: alias))
}
/**
@@ -158,9 +158,9 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
@objc
public static func objectIDAs(alias: KeyPath? = nil) -> CSSelectTerm {
public static func objectIDAs(_ alias: KeyPath? = nil) -> CSSelectTerm {
return self.init(.ObjectID(As: alias))
return self.init(.objectID(As: alias))
}
@@ -171,7 +171,7 @@ public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSSelectTerm else {
@@ -274,7 +274,7 @@ public final class CSSelect: NSObject {
*/
public convenience init(dateTerm: CSSelectTerm) {
self.init(Select<NSDate>(dateTerm.bridgeToSwift))
self.init(Select<Date>(dateTerm.bridgeToSwift))
}
/**
@@ -290,7 +290,7 @@ public final class CSSelect: NSObject {
*/
public convenience init(dataTerm: CSSelectTerm) {
self.init(Select<NSData>(dataTerm.bridgeToSwift))
self.init(Select<Data>(dataTerm.bridgeToSwift))
}
/**
@@ -306,7 +306,7 @@ public final class CSSelect: NSObject {
*/
public convenience init(objectIDTerm: ()) {
self.init(Select<NSManagedObjectID>(.ObjectID()))
self.init(Select<NSManagedObjectID>(.objectID()))
}
/**
@@ -320,7 +320,7 @@ public final class CSSelect: NSObject {
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
- returns: a `CSSelect` clause for querying an entity attribute
*/
public static func dictionaryForTerm(term: CSSelectTerm) -> CSSelect {
public static func dictionaryForTerm(_ term: CSSelectTerm) -> CSSelect {
return self.init(Select<NSDictionary>(term.bridgeToSwift))
}
@@ -339,7 +339,7 @@ public final class CSSelect: NSObject {
- parameter terms: the `CSSelectTerm`s specifying the attribute/aggregate values to query
- returns: a `CSSelect` clause for querying an entity attribute
*/
public static func dictionaryForTerms(terms: [CSSelectTerm]) -> CSSelect {
public static func dictionaryForTerms(_ terms: [CSSelectTerm]) -> CSSelect {
return self.init(Select<NSDictionary>(terms.map { $0.bridgeToSwift }))
}
@@ -353,7 +353,7 @@ public final class CSSelect: NSObject {
^ self.selectTerms.map { $0.hashValue }.reduce(0, combine: ^)
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSSelect else {
@@ -381,7 +381,7 @@ public final class CSSelect: NSObject {
public init<T: SelectResultType>(_ swiftValue: Select<T>) {
self.attributeType = .UndefinedAttributeType
self.attributeType = .undefinedAttributeType
self.selectTerms = swiftValue.selectTerms
self.bridgeToSwift = swiftValue
super.init()
+6 -6
View File
@@ -76,7 +76,7 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (storage: CSStorageInterface) -> Void, @noescape failure: (error: NSError) -> Void) {
public func handleSuccess(@noescape _ success: (storage: CSStorageInterface) -> Void, @noescape failure: (error: NSError) -> Void) {
if let storage = self.storage {
@@ -96,7 +96,7 @@ 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.
*/
@objc
public func handleSuccess(@noescape success: (storage: CSStorageInterface) -> Void) {
public func handleSuccess(@noescape _ success: (storage: CSStorageInterface) -> Void) {
guard let storage = self.storage else {
@@ -113,7 +113,7 @@ 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.
*/
@objc
public func handleFailure(@noescape failure: (error: NSError) -> Void) {
public func handleFailure(@noescape _ failure: (error: NSError) -> Void) {
guard let error = self.error else {
@@ -134,7 +134,7 @@ public final class CSSetupResult: NSObject {
return self.isSuccess.hashValue ^ self.error!.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSSetupResult else {
@@ -156,11 +156,11 @@ public final class CSSetupResult: NSObject {
switch swiftValue {
case .Success(let storage):
case .success(let storage):
self.storage = storage.bridgeToObjectiveC
self.error = nil
case .Failure(let error):
case .failure(let error):
self.storage = nil
self.error = error.bridgeToObjectiveC
}
+7 -7
View File
@@ -70,22 +70,22 @@ public enum CSLocalStorageOptions: Int {
/**
Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch
*/
case None = 0
case none = 0
/**
Tells the `DataStack` to delete and recreate the store on model mismatch, otherwise exceptions will be thrown on failure instead
*/
case RecreateStoreOnModelMismatch = 1
case recreateStoreOnModelMismatch = 1
/**
Tells the `DataStack` to prevent progressive migrations for the store
*/
case PreventProgressiveMigration = 2
case preventProgressiveMigration = 2
/**
Tells the `DataStack` to allow lightweight migration for the store when added synchronously
*/
case AllowSynchronousLightweightMigration = 4
case allowSynchronousLightweightMigration = 4
}
@@ -103,13 +103,13 @@ public protocol CSLocalStorage: CSStorageInterface {
The `NSURL` that points to the store file
*/
@objc
var fileURL: NSURL { get }
var fileURL: URL { get }
/**
The `NSBundle`s from which to search mapping models for migrations
*/
@objc
var mappingModelBundles: [NSBundle] { get }
var mappingModelBundles: [Bundle] { get }
/**
Options that tell the `CSDataStack` how to setup the persistent store
@@ -121,5 +121,5 @@ public protocol CSLocalStorage: CSStorageInterface {
Called by the `CSDataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. Implementers can use the `sourceModel` to perform necessary store operations. (SQLite stores for example, can convert WAL journaling mode to DELETE before deleting)
*/
@objc
func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel, error: NSErrorPointer) -> Bool
func eraseStorageAndWait(soureModel: NSManagedObjectModel, error: NSErrorPointer) -> Bool
}
@@ -58,7 +58,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
- returns: a `CSSaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
@objc
public func beginSynchronous(closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
public func beginSynchronous(_ closure: (transaction: CSSynchronousDataTransaction) -> Void) -> CSSaveResult? {
return bridge {
@@ -87,7 +87,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
@objc
public override func createInto(into: CSInto) -> AnyObject {
public override func createInto(_ into: CSInto) -> AnyObject {
return self.bridgeToSwift.create(into.bridgeToSwift)
}
@@ -100,7 +100,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public override func editObject(object: NSManagedObject?) -> AnyObject? {
public override func editObject(_ object: NSManagedObject?) -> AnyObject? {
return self.bridgeToSwift.edit(object)
}
@@ -114,7 +114,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public override func editInto(into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
public override func editInto(_ into: CSInto, objectID: NSManagedObjectID) -> AnyObject? {
return self.bridgeToSwift.edit(into.bridgeToSwift, objectID)
}
@@ -125,7 +125,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
- parameter object: the `NSManagedObject` type to be deleted
*/
@objc
public override func deleteObject(object: NSManagedObject?) {
public override func deleteObject(_ object: NSManagedObject?) {
return self.bridgeToSwift.delete(object)
}
@@ -135,7 +135,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction {
- parameter objects: the `NSManagedObject`s to be deleted
*/
public override func deleteObjects(objects: [NSManagedObject]) {
public override func deleteObjects(_ objects: [NSManagedObject]) {
self.bridgeToSwift.delete(objects)
}
+3 -3
View File
@@ -41,7 +41,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
The block to customize the `NSFetchRequest`
*/
@objc
public var block: (fetchRequest: NSFetchRequest) -> Void {
public var block: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void {
return self.bridgeToSwift.closure
}
@@ -53,7 +53,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
- parameter block: the block to customize the `NSFetchRequest`
*/
@objc
public convenience init(block: (fetchRequest: NSFetchRequest) -> Void) {
public convenience init(block: (fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) {
self.init(Tweak(block))
}
@@ -70,7 +70,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
// MARK: CSFetchClause, CSQueryClause, CSDeleteClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
@@ -43,7 +43,7 @@ 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.
*/
@objc
public func commit(completion: ((result: CSSaveResult) -> Void)?) {
public func commit(_ completion: ((result: CSSaveResult) -> Void)?) {
self.bridgeToSwift.commit { (result) in
@@ -110,7 +110,7 @@ public final class CSUnsafeDataTransaction: CSBaseDataTransaction {
- parameter closure: the closure where changes can be made prior to the flush
*/
@objc
public func flush(block: () -> Void) {
public func flush(_ block: () -> Void) {
self.bridgeToSwift.flush {
@@ -142,7 +142,7 @@ public final class CSUnsafeDataTransaction: CSBaseDataTransaction {
*/
@objc
@warn_unused_result
public func beginUnsafeWithSupportsUndo(supportsUndo: Bool) -> CSUnsafeDataTransaction {
public func beginUnsafeWithSupportsUndo(_ supportsUndo: Bool) -> CSUnsafeDataTransaction {
return bridge {
+4 -4
View File
@@ -41,7 +41,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
The internal `NSPredicate` instance for the `Where` clause
*/
@objc
public var predicate: NSPredicate {
public var predicate: Predicate {
return self.bridgeToSwift.predicate
}
@@ -110,7 +110,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
- parameter predicate: the `NSPredicate` for the fetch or query
*/
@objc
public convenience init(predicate: NSPredicate) {
public convenience init(predicate: Predicate) {
self.init(Where(predicate))
}
@@ -123,7 +123,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
public override func isEqual(_ object: AnyObject?) -> Bool {
guard let object = object as? CSWhere else {
@@ -141,7 +141,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
// MARK: CSFetchClause, CSQueryClause, CSDeleteClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
public func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
+16 -16
View File
@@ -79,17 +79,17 @@ public extension CoreStoreSwiftType where ObjectiveCType: CoreStoreObjectiveCTyp
// MARK: - Internal
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape closure: () -> T) -> T.ObjectiveCType {
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape _ closure: () -> T) -> T.ObjectiveCType {
return closure().bridgeToObjectiveC
}
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape closure: () -> T?) -> T.ObjectiveCType? {
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape _ closure: () -> T?) -> T.ObjectiveCType? {
return closure()?.bridgeToObjectiveC
}
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape closure: () throws -> T) throws -> T.ObjectiveCType {
internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObjectiveCType, T == T.ObjectiveCType.SwiftType>(@noescape _ closure: () throws -> T) throws -> T.ObjectiveCType {
do {
@@ -101,7 +101,7 @@ internal func bridge<T: CoreStoreSwiftType where T.ObjectiveCType: CoreStoreObje
}
}
internal func bridge(@noescape closure: () throws -> Void) throws {
internal func bridge(@noescape _ closure: () throws -> Void) throws {
do {
@@ -113,62 +113,62 @@ internal func bridge(@noescape closure: () throws -> Void) throws {
}
}
internal func bridge<T: CoreStoreSwiftType>(error: NSErrorPointer, @noescape _ closure: () throws -> T) -> T.ObjectiveCType? {
internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, @noescape _ closure: () throws -> T) -> T.ObjectiveCType? {
do {
let result = try closure()
error.memory = nil
error?.pointee = nil
return result.bridgeToObjectiveC
}
catch let swiftError {
error.memory = swiftError.bridgeToObjectiveC
error?.pointee = swiftError.bridgeToObjectiveC
return nil
}
}
internal func bridge(error: NSErrorPointer, @noescape _ closure: () throws -> Void) -> Bool {
internal func bridge(_ error: NSErrorPointer, @noescape _ closure: () throws -> Void) -> Bool {
do {
try closure()
error.memory = nil
error?.pointee = nil
return true
}
catch let swiftError {
error.memory = swiftError.bridgeToObjectiveC
error?.pointee = swiftError.bridgeToObjectiveC
return false
}
}
internal func bridge<T>(error: NSErrorPointer, @noescape _ closure: () throws -> T?) -> T? {
internal func bridge<T>(_ error: NSErrorPointer, @noescape _ closure: () throws -> T?) -> T? {
do {
let result = try closure()
error.memory = nil
error?.pointee = nil
return result
}
catch let swiftError {
error.memory = swiftError.bridgeToObjectiveC
error?.pointee = swiftError.bridgeToObjectiveC
return nil
}
}
internal func bridge<T: CoreStoreSwiftType>(error: NSErrorPointer, @noescape _ closure: () throws -> [T]) -> [T.ObjectiveCType]? {
internal func bridge<T: CoreStoreSwiftType>(_ error: NSErrorPointer, @noescape _ closure: () throws -> [T]) -> [T.ObjectiveCType]? {
do {
let result = try closure()
error.memory = nil
error?.pointee = nil
return result.map { $0.bridgeToObjectiveC }
}
catch let swiftError {
error.memory = swiftError.bridgeToObjectiveC
error?.pointee = swiftError.bridgeToObjectiveC
return nil
}
}
@@ -27,40 +27,40 @@ import Foundation
import CoreData
#if os(iOS) || os(watchOS) || os(tvOS)
// MARK: - NSFetchedResultsController
public extension NSFetchedResultsController {
/**
Utility for creating an `NSFetchedResultsController` from a `CSDataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `CSListMonitor`s abstractio
- parameter dataStack: the `CSDataStack` to observe objects from
- parameter fetchRequest: the `NSFetchRequest` instance to use with the `NSFetchedResultsController`
- parameter from: an optional `CSFrom` clause indicating the entity type. If not specified, the `fetchRequest` argument's `entity` property should already be set.
- parameter sectionBy: a `CSSectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
@objc
public static func cs_createForStack(dataStack: CSDataStack, fetchRequest: NSFetchRequest, from: CSFrom?, sectionBy: CSSectionBy?, fetchClauses: [CSFetchClause]) -> NSFetchedResultsController {
return CoreStoreFetchedResultsController(
context: dataStack.bridgeToSwift.mainContext,
fetchRequest: fetchRequest,
from: from?.bridgeToSwift,
sectionBy: sectionBy?.bridgeToSwift,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(CSOrderBy)) clause or any custom \(cs_typeName(CSFetchClause)) that provides a sort descriptor."
)
}
)
}
}
#endif
//#if os(iOS) || os(watchOS) || os(tvOS)
//
//// MARK: - NSFetchedResultsController
//
//public extension NSFetchedResultsController {
//
// /**
// Utility for creating an `NSFetchedResultsController` from a `CSDataStack`. This is useful when an `NSFetchedResultsController` is preferred over the overhead of `CSListMonitor`s abstractio
//
// - parameter dataStack: the `CSDataStack` to observe objects from
// - parameter fetchRequest: the `NSFetchRequest` instance to use with the `NSFetchedResultsController`
// - parameter from: an optional `CSFrom` clause indicating the entity type. If not specified, the `fetchRequest` argument's `entity` property should already be set.
// - parameter sectionBy: a `CSSectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
// - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
// */
// @objc
// public static func cs_createForStack(_ dataStack: CSDataStack, fetchRequest: NSFetchRequest<NSFetchRequestResult>, from: CSFrom?, sectionBy: CSSectionBy?, fetchClauses: [CSFetchClause]) -> NSFetchedResultsController {
//
// return CoreStoreFetchedResultsController(
// context: dataStack.bridgeToSwift.mainContext,
// fetchRequest: fetchRequest,
// from: from?.bridgeToSwift,
// sectionBy: sectionBy?.bridgeToSwift,
// applyFetchClauses: { fetchRequest in
//
// fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
//
// CoreStore.assert(
// fetchRequest.sortDescriptors?.isEmpty == false,
// "An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(CSOrderBy)) clause or any custom \(cs_typeName(CSFetchClause)) that provides a sort descriptor."
// )
// }
// )
// }
//}
//
//#endif
@@ -39,7 +39,7 @@ public extension NSManagedObject {
*/
@objc
@warn_unused_result
public func cs_accessValueForKVCKey(KVCKey: KeyPath) -> AnyObject? {
public func cs_accessValueForKVCKey(_ KVCKey: KeyPath) -> AnyObject? {
return self.accessValueForKVCKey(KVCKey)
}
@@ -51,7 +51,7 @@ public extension NSManagedObject {
- parameter KVCKey: the KVC key
*/
@objc
public func cs_setValue(value: AnyObject?, forKVCKey KVCKey: KeyPath) {
public func cs_setValue(_ value: AnyObject?, forKVCKey KVCKey: KeyPath) {
self.setValue(value, forKVCKey: KVCKey)
}
@@ -34,43 +34,43 @@ internal extension NSManagedObjectContext {
// MARK: Internal
@nonobjc
internal func fetchOne(from: CSFrom, _ fetchClauses: [CSFetchClause]) -> NSManagedObject? {
internal func fetchOne(_ from: CSFrom, _ fetchClauses: [CSFetchClause]) -> NSManagedObject? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObject>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchOne(fetchRequest)
return self.fetchOne(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchAll(from: CSFrom, _ fetchClauses: [CSFetchClause]) -> [NSManagedObject]? {
internal func fetchAll<T: NSManagedObject>(_ from: CSFrom, _ fetchClauses: [CSFetchClause]) -> [T]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchAll(fetchRequest)
return self.fetchAll(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchCount(from: CSFrom, _ fetchClauses: [CSFetchClause]) -> Int? {
internal func fetchCount(_ from: CSFrom, _ fetchClauses: [CSFetchClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObject>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
@@ -78,51 +78,51 @@ internal extension NSManagedObjectContext {
return nil
}
return self.fetchCount(fetchRequest)
return self.fetchCount(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchObjectID(from: CSFrom, _ fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
internal func fetchObjectID(_ from: CSFrom, _ fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObjectID>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectIDResultType
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchObjectID(fetchRequest)
return self.fetchObjectID(fetchRequest.dynamicCast())
}
@nonobjc
internal func fetchObjectIDs(from: CSFrom, _ fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
internal func fetchObjectIDs(_ from: CSFrom, _ fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObjectID>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectIDResultType
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
guard storeFound else {
return nil
}
return self.fetchObjectIDs(fetchRequest)
return self.fetchObjectIDs(fetchRequest.dynamicCast())
}
@nonobjc
internal func deleteAll(from: CSFrom, _ deleteClauses: [CSDeleteClause]) -> Int? {
internal func deleteAll(_ from: CSFrom, _ deleteClauses: [CSDeleteClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSManagedObject>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchRequest.returnsObjectsAsFaults = true
fetchRequest.includesPropertyValues = false
deleteClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
@@ -131,13 +131,13 @@ internal extension NSManagedObjectContext {
return nil
}
return self.deleteAll(fetchRequest)
return self.deleteAll(fetchRequest.dynamicCast())
}
@nonobjc
internal func queryValue(from: CSFrom, _ selectClause: CSSelect, _ queryClauses: [CSQueryClause]) -> AnyObject? {
internal func queryValue(_ from: CSFrom, _ selectClause: CSSelect, _ queryClauses: [CSQueryClause]) -> AnyObject? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSFetchRequestResult>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
@@ -150,13 +150,13 @@ internal extension NSManagedObjectContext {
return nil
}
return self.queryValue(selectTerms, fetchRequest: fetchRequest)
return self.queryValue(selectTerms, fetchRequest: fetchRequest.dynamicCast())
}
@nonobjc
internal func queryAttributes(from: CSFrom, _ selectClause: CSSelect, _ queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
internal func queryAttributes(_ from: CSFrom, _ selectClause: CSSelect, _ queryClauses: [CSQueryClause]) -> [[NSString: AnyObject]]? {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<NSFetchRequestResult>()
let storeFound = from.bridgeToSwift.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
@@ -168,6 +168,6 @@ internal extension NSManagedObjectContext {
return nil
}
return self.queryAttributes(fetchRequest)
return self.queryAttributes(fetchRequest.dynamicCast())
}
}
@@ -28,7 +28,7 @@ import Foundation
// MARK: - NSProgress
public extension NSProgress {
public extension Progress {
/**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
@@ -36,7 +36,7 @@ public extension NSProgress {
- parameter closure: the closure to execute on progress change
*/
@objc
public func cs_setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
public func cs_setProgressHandler(_ closure: ((progress: Progress) -> Void)?) {
self.setProgressHandler(closure)
}
+9 -9
View File
@@ -40,7 +40,7 @@ public extension CoreStore {
- returns: a `ObjectMonitor` that monitors changes to `object`
*/
@warn_unused_result
public static func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {
public static func monitorObject<T: NSManagedObject>(_ object: T) -> ObjectMonitor<T> {
return self.defaultStack.monitorObject(object)
}
@@ -53,7 +53,7 @@ public extension CoreStore {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public static func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public static func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.defaultStack.monitorList(from, fetchClauses)
}
@@ -66,7 +66,7 @@ public extension CoreStore {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public static func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public static func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
return self.defaultStack.monitorList(from, fetchClauses)
}
@@ -78,7 +78,7 @@ public extension CoreStore {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public static func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
public static func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
self.defaultStack.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses)
}
@@ -90,7 +90,7 @@ public extension CoreStore {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public static func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
public static func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
self.defaultStack.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses)
}
@@ -104,7 +104,7 @@ public extension CoreStore {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public static func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public static func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.defaultStack.monitorSectionedList(from, sectionBy, fetchClauses)
}
@@ -118,7 +118,7 @@ public extension CoreStore {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public static func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public static func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
return self.defaultStack.monitorSectionedList(from, sectionBy, fetchClauses)
}
@@ -131,7 +131,7 @@ public extension CoreStore {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public static func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
public static func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
self.defaultStack.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses)
}
@@ -144,7 +144,7 @@ public extension CoreStore {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public static func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
public static func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
self.defaultStack.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses)
}
+18 -18
View File
@@ -43,10 +43,10 @@ public extension DataStack {
- returns: a `ObjectMonitor` that monitors changes to `object`
*/
@warn_unused_result
public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {
public func monitorObject<T: NSManagedObject>(_ object: T) -> ObjectMonitor<T> {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
return ObjectMonitor(dataStack: self, object: object)
@@ -60,7 +60,7 @@ public extension DataStack {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.monitorList(from, fetchClauses)
}
@@ -73,10 +73,10 @@ public extension DataStack {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
return ListMonitor(
@@ -89,7 +89,7 @@ public extension DataStack {
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor."
"An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor."
)
}
)
@@ -102,7 +102,7 @@ public extension DataStack {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
public func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses)
}
@@ -114,10 +114,10 @@ public extension DataStack {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
public func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
_ = ListMonitor(
@@ -130,7 +130,7 @@ public extension DataStack {
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor."
"An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor."
)
},
createAsynchronously: createAsynchronously
@@ -146,7 +146,7 @@ public extension DataStack {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.monitorSectionedList(from, sectionBy, fetchClauses)
}
@@ -160,10 +160,10 @@ public extension DataStack {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
@@ -177,7 +177,7 @@ public extension DataStack {
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor."
"An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor."
)
}
)
@@ -191,7 +191,7 @@ public extension DataStack {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses)
}
@@ -204,10 +204,10 @@ public extension DataStack {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to observe objects from \(cs_typeName(self)) outside the main thread."
)
@@ -221,7 +221,7 @@ public extension DataStack {
CoreStore.assert(
fetchRequest.sortDescriptors?.isEmpty == false,
"An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor."
"An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor."
)
},
createAsynchronously: createAsynchronously
+105 -105
View File
@@ -111,7 +111,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
*/
public subscript(sectionIndex: Int, itemIndex: Int) -> T {
return self[NSIndexPath(indexes: [sectionIndex, itemIndex], length: 2)]
return self[NSIndexPath(indexes: [sectionIndex, itemIndex], length: 2) as IndexPath]
}
/**
@@ -140,13 +140,13 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will raise an exception.
- returns: the `NSManagedObject` at the specified index path
*/
public subscript(indexPath: NSIndexPath) -> T {
public subscript(indexPath: IndexPath) -> T {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.objectAtIndexPath(indexPath) as! T
return self.fetchedResultsController.object(at: indexPath) as! T
}
/**
@@ -155,11 +155,11 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`.
- returns: the `NSManagedObject` at the specified index path, or `nil` if out of bounds
*/
public subscript(safeIndexPath indexPath: NSIndexPath) -> T? {
public subscript(safeIndexPath indexPath: IndexPath) -> T? {
return self[
safeSectionIndex: indexPath.indexAtPosition(0),
safeItemIndex: indexPath.indexAtPosition(1)
safeSectionIndex: indexPath[0],
safeItemIndex: indexPath[1]
]
}
@@ -192,7 +192,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: `true` if at least one object in the specified section exists, `false` otherwise
*/
@warn_unused_result
public func hasObjectsInSection(section: Int) -> Bool {
public func hasObjectsInSection(_ section: Int) -> Bool {
return self.numberOfObjectsInSection(safeSectionIndex: section) > 0
}
@@ -206,7 +206,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func objectsInAllSections() -> [T] {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return (self.fetchedResultsController.fetchedObjects as? [T]) ?? []
@@ -219,7 +219,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: all objects in the specified section
*/
@warn_unused_result
public func objectsInSection(section: Int) -> [T] {
public func objectsInSection(_ section: Int) -> [T] {
return (self.sectionInfoAtIndex(section).objects as? [T]) ?? []
}
@@ -245,7 +245,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func numberOfSections() -> Int {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.sections?.count ?? 0
@@ -260,7 +260,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func numberOfObjects() -> Int {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.fetchedObjects?.count ?? 0
@@ -273,7 +273,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: the number of objects in the specified section
*/
@warn_unused_result
public func numberOfObjectsInSection(section: Int) -> Int {
public func numberOfObjectsInSection(_ section: Int) -> Int {
return self.sectionInfoAtIndex(section).numberOfObjects
}
@@ -297,10 +297,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: the `NSFetchedResultsSectionInfo` for the specified section
*/
@warn_unused_result
public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo {
public func sectionInfoAtIndex(_ section: Int) -> NSFetchedResultsSectionInfo {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.sections![section]
@@ -316,7 +316,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func sectionInfoAtIndex(safeSectionIndex section: Int) -> NSFetchedResultsSectionInfo? {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
guard section >= 0 else {
@@ -340,7 +340,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func sections() -> [NSFetchedResultsSectionInfo] {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.sections ?? []
@@ -354,13 +354,13 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: the target section for the specified "Section Index" title and index.
*/
@warn_unused_result
public func targetSectionForSectionIndex(title title: String, index: Int) -> Int {
public func targetSectionForSectionIndex(title: String, index: Int) -> Int {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index)
return self.fetchedResultsController.section(forSectionIndexTitle: title, at: index)
}
/**
@@ -372,7 +372,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
public func sectionIndexTitles() -> [String] {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.sectionIndexTitles
@@ -385,13 +385,13 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
*/
@warn_unused_result
public func indexOf(object: T) -> Int? {
public func indexOf(_ object: T) -> Int? {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return (self.fetchedResultsController.fetchedObjects as? [T] ?? []).indexOf(object)
return (self.fetchedResultsController.fetchedObjects as? [T] ?? []).index(of: object)
}
/**
@@ -401,13 +401,13 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- returns: the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
*/
@warn_unused_result
public func indexPathOf(object: T) -> NSIndexPath? {
public func indexPathOf(_ object: T) -> IndexPath? {
CoreStore.assert(
!self.isPendingRefetch || NSThread.isMainThread(),
!self.isPendingRefetch || Thread.isMainThread,
"Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress."
)
return self.fetchedResultsController.indexPathForObject(object)
return self.fetchedResultsController.indexPath(forObject: object)
}
@@ -424,7 +424,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- 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 where U.ListEntityType == T>(_ observer: U) {
self.unregisterObserver(observer)
self.registerObserver(
@@ -459,7 +459,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- 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 where U.ListEntityType == T>(_ observer: U) {
self.unregisterObserver(observer)
self.registerObserver(
@@ -513,7 +513,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- 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 where U.ListEntityType == T>(_ observer: U) {
self.unregisterObserver(observer)
self.registerObserver(
@@ -574,7 +574,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter observer: a `ListObserver` to unregister notifications to
*/
public func removeObserver<U: ListObserver where U.ListEntityType == T>(observer: U) {
public func removeObserver<U: ListObserver where U.ListEntityType == T>(_ observer: U) {
self.unregisterObserver(observer)
}
@@ -594,7 +594,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values.
*/
public func refetch(fetchClauses: FetchClause...) {
public func refetch(_ fetchClauses: FetchClause...) {
self.refetch(fetchClauses)
}
@@ -606,7 +606,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values.
*/
public func refetch(fetchClauses: [FetchClause]) {
public func refetch(_ fetchClauses: [FetchClause]) {
self.refetch { (fetchRequest) in
@@ -625,7 +625,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
// MARK: Internal
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) {
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
self.init(
context: dataStack.mainContext,
@@ -637,7 +637,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> 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(
context: dataStack.mainContext,
@@ -649,7 +649,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) {
internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
self.init(
context: unsafeTransaction.context,
@@ -661,7 +661,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> 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(
context: unsafeTransaction.context,
@@ -675,10 +675,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
internal func upcast() -> ListMonitor<NSManagedObject> {
return unsafeBitCast(self, ListMonitor<NSManagedObject>.self)
return unsafeBitCast(self, to: ListMonitor<NSManagedObject>.self)
}
internal func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>) -> Void) {
internal func registerChangeNotification(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -698,7 +698,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, object: T, indexPath: NSIndexPath?, newIndexPath: NSIndexPath?) -> Void) {
internal func registerObjectNotification(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, object: T, indexPath: IndexPath?, newIndexPath: IndexPath?) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -707,7 +707,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
closure: { [weak self] (note) -> Void in
guard let `self` = self,
let userInfo = note.userInfo,
let userInfo = (note as NSNotification).userInfo,
let object = userInfo[UserInfoKeyObject] as? T else {
return
@@ -715,8 +715,8 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
callback(
monitor: self,
object: object,
indexPath: userInfo[UserInfoKeyIndexPath] as? NSIndexPath,
newIndexPath: userInfo[UserInfoKeyNewIndexPath] as? NSIndexPath
indexPath: userInfo[UserInfoKeyIndexPath] as? IndexPath,
newIndexPath: userInfo[UserInfoKeyNewIndexPath] as? IndexPath
)
}
),
@@ -725,7 +725,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal func registerSectionNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, sectionIndex: Int) -> Void) {
internal func registerSectionNotification(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, sectionIndex: Int) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -734,9 +734,9 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
closure: { [weak self] (note) -> Void in
guard let `self` = self,
let userInfo = note.userInfo,
let userInfo = (note as NSNotification).userInfo,
let sectionInfo = userInfo[UserInfoKeySectionInfo] as? NSFetchedResultsSectionInfo,
let sectionIndex = (userInfo[UserInfoKeySectionIndex] as? NSNumber)?.integerValue else {
let sectionIndex = (userInfo[UserInfoKeySectionIndex] as? NSNumber)?.intValue else {
return
}
@@ -752,10 +752,10 @@ 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: (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) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread."
)
self.registerChangeNotification(
@@ -812,10 +812,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal func registerObserver<U: AnyObject>(observer: U, didInsertObject: (observer: U, monitor: ListMonitor<T>, object: T, toIndexPath: NSIndexPath) -> Void, didDeleteObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: NSIndexPath) -> Void, didUpdateObject: (observer: U, monitor: ListMonitor<T>, object: T, atIndexPath: NSIndexPath) -> Void, didMoveObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void) {
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) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread."
)
@@ -894,10 +894,10 @@ 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: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, toIndex: Int) -> Void, didDeleteSection: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, fromIndex: Int) -> Void) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread."
)
@@ -939,10 +939,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
}
internal func unregisterObserver(observer: AnyObject) {
internal func unregisterObserver(_ observer: AnyObject) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to remove an observer of type \(cs_typeName(observer)) outside the main thread."
)
let nilValue: AnyObject? = nil
@@ -960,10 +960,10 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
cs_setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteSectionKey, inObject: observer)
}
internal func refetch(applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) {
internal func refetch(_ applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to refetch a \(cs_typeName(self)) outside the main thread."
)
@@ -971,14 +971,14 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
self.isPendingRefetch = true
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorWillRefetchListNotification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorWillRefetchListNotification),
object: self
)
}
self.applyFetchClauses = applyFetchClauses
self.taskGroup.notify(.Main) { [weak self] () -> Void in
self.taskGroup.notify(.main) { [weak self] () -> Void in
guard let `self` = self else {
@@ -997,7 +997,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
try! self.fetchedResultsController.performFetchFromSpecifiedStores()
GCDQueue.Main.async { [weak self] () -> Void in
GCDQueue.main.async { [weak self] () -> Void in
guard let `self` = self else {
@@ -1007,8 +1007,8 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
self.fetchedResultsControllerDelegate.enabled = true
self.isPendingRefetch = false
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidRefetchListNotification,
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: ListMonitorDidRefetchListNotification),
object: self
)
}
@@ -1039,13 +1039,13 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
private var didDeleteSectionKey: Void?
private let fetchedResultsController: CoreStoreFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<T>
private let sectionIndexTransformer: (sectionName: KeyPath?) -> String?
private var observerForWillChangePersistentStore: NotificationObserver!
private var observerForDidChangePersistentStore: NotificationObserver!
private let taskGroup = GCDGroup()
private let transactionQueue: GCDQueue
private var applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void
private var applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void
private var isPersistentStoreChanging: Bool = false {
@@ -1068,24 +1068,24 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
}
}
private init(context: NSManagedObjectContext, transactionQueue: GCDQueue, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void, createAsynchronously: ((ListMonitor<T>) -> Void)?) {
private init(context: NSManagedObjectContext, transactionQueue: GCDQueue, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest<NSManagedObject>) -> Void, createAsynchronously: ((ListMonitor<T>) -> Void)?) {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<T>()
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchRequest.fetchBatchSize = 20
fetchRequest.includesPendingChanges = false
fetchRequest.shouldRefreshRefetchedObjects = true
let fetchedResultsController = CoreStoreFetchedResultsController(
context: context,
fetchRequest: fetchRequest,
fetchRequest: fetchRequest.dynamicCast(),
from: from,
sectionBy: sectionBy,
applyFetchClauses: applyFetchClauses
)
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate()
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate<T>()
self.fetchedResultsController = fetchedResultsController
self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate
@@ -1110,9 +1110,9 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
}
self.observerForWillChangePersistentStore = NotificationObserver(
notificationName: NSPersistentStoreCoordinatorStoresWillChangeNotification,
notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresWillChange.rawValue,
object: coordinator,
queue: NSOperationQueue.mainQueue(),
queue: OperationQueue.main,
closure: { [weak self] (note) -> Void in
guard let `self` = self else {
@@ -1123,7 +1123,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
self.isPersistentStoreChanging = true
guard let removedStores = (note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore]).flatMap(Set.init)
where !Set(self.fetchedResultsController.fetchRequest.affectedStores ?? []).intersect(removedStores).isEmpty else {
where !Set(self.fetchedResultsController.fetchRequest.affectedStores ?? []).intersection(removedStores).isEmpty else {
return
}
@@ -1132,9 +1132,9 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
)
self.observerForDidChangePersistentStore = NotificationObserver(
notificationName: NSPersistentStoreCoordinatorStoresDidChangeNotification,
notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresDidChange.rawValue,
object: coordinator,
queue: NSOperationQueue.mainQueue(),
queue: OperationQueue.main,
closure: { [weak self] (note) -> Void in
guard let `self` = self else {
@@ -1146,7 +1146,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
let previousStores = Set(self.fetchedResultsController.fetchRequest.affectedStores ?? [])
let currentStores = previousStores
.subtract(note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore] ?? [])
.subtracting(note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore] ?? [])
.union(note.userInfo?[NSAddedPersistentStoresKey] as? [NSPersistentStore] ?? [])
if previousStores != currentStores {
@@ -1164,7 +1164,7 @@ public final class ListMonitor<T: NSManagedObject>: Hashable {
transactionQueue.async {
try! fetchedResultsController.performFetchFromSpecifiedStores()
self.taskGroup.notify(.Main) {
self.taskGroup.notify(.main) {
createAsynchronously(self)
}
@@ -1213,13 +1213,13 @@ extension ListMonitor: FetchedResultsControllerHandler {
// MARK: FetchedResultsControllerHandler
internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeObject anObject: AnyObject, atIndexPath indexPath: IndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .Insert:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidInsertObjectNotification,
case .insert:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidInsertObjectNotification),
object: self,
userInfo: [
UserInfoKeyObject: anObject,
@@ -1227,9 +1227,9 @@ extension ListMonitor: FetchedResultsControllerHandler {
]
)
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidDeleteObjectNotification,
case .delete:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidDeleteObjectNotification),
object: self,
userInfo: [
UserInfoKeyObject: anObject,
@@ -1237,9 +1237,9 @@ extension ListMonitor: FetchedResultsControllerHandler {
]
)
case .Update:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidUpdateObjectNotification,
case .update:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidUpdateObjectNotification),
object: self,
userInfo: [
UserInfoKeyObject: anObject,
@@ -1247,9 +1247,9 @@ extension ListMonitor: FetchedResultsControllerHandler {
]
)
case .Move:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidMoveObjectNotification,
case .move:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidMoveObjectNotification),
object: self,
userInfo: [
UserInfoKeyObject: anObject,
@@ -1260,27 +1260,27 @@ extension ListMonitor: FetchedResultsControllerHandler {
}
}
internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidInsertSectionNotification,
case .insert:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidInsertSectionNotification),
object: self,
userInfo: [
UserInfoKeySectionInfo: sectionInfo,
UserInfoKeySectionIndex: NSNumber(integer: sectionIndex)
UserInfoKeySectionIndex: NSNumber(value: sectionIndex)
]
)
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidDeleteSectionNotification,
case .delete:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidDeleteSectionNotification),
object: self,
userInfo: [
UserInfoKeySectionInfo: sectionInfo,
UserInfoKeySectionIndex: NSNumber(integer: sectionIndex)
UserInfoKeySectionIndex: NSNumber(value: sectionIndex)
]
)
@@ -1289,25 +1289,25 @@ extension ListMonitor: FetchedResultsControllerHandler {
}
}
internal func controllerWillChangeContent(controller: NSFetchedResultsController) {
internal func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.taskGroup.enter()
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorWillChangeListNotification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorWillChangeListNotification),
object: self
)
}
internal func controllerDidChangeContent(controller: NSFetchedResultsController) {
internal func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
NSNotificationCenter.defaultCenter().postNotificationName(
ListMonitorDidChangeListNotification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: ListMonitorDidChangeListNotification),
object: self
)
self.taskGroup.leave()
}
internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, sectionIndexTitleForSectionName sectionName: String?) -> String? {
return self.sectionIndexTransformer(sectionName: sectionName)
}
+20 -20
View File
@@ -53,28 +53,28 @@ public protocol ListObserver: class {
- parameter monitor: the `ListMonitor` monitoring the list being observed
*/
func listMonitorWillChange(monitor: ListMonitor<ListEntityType>)
func listMonitorWillChange(_ monitor: ListMonitor<ListEntityType>)
/**
Handles processing right after a change to the observed list occurs
- parameter monitor: the `ListMonitor` monitoring the object being observed
*/
func listMonitorDidChange(monitor: ListMonitor<ListEntityType>)
func listMonitorDidChange(_ monitor: ListMonitor<ListEntityType>)
/**
This method is broadcast from within the `ListMonitor`'s `refetch(...)` method to let observers prepare for the internal `NSFetchedResultsController`'s pending change to its predicate, sort descriptors, etc. Note that the actual refetch will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes.
- parameter monitor: the `ListMonitor` monitoring the object being observed
*/
func listMonitorWillRefetch(monitor: ListMonitor<ListEntityType>)
func listMonitorWillRefetch(_ monitor: ListMonitor<ListEntityType>)
/**
After the `ListMonitor`'s `refetch(...)` method is called, this method is broadcast after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes.
- parameter monitor: the `ListMonitor` monitoring the object being observed
*/
func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>)
func listMonitorDidRefetch(_ monitor: ListMonitor<ListEntityType>)
}
@@ -85,22 +85,22 @@ public extension ListObserver {
/**
The default implementation does nothing.
*/
func listMonitorWillChange(monitor: ListMonitor<ListEntityType>) { }
func listMonitorWillChange(_ monitor: ListMonitor<ListEntityType>) { }
/**
The default implementation does nothing.
*/
func listMonitorDidChange(monitor: ListMonitor<ListEntityType>) { }
func listMonitorDidChange(_ monitor: ListMonitor<ListEntityType>) { }
/**
The default implementation does nothing.
*/
func listMonitorWillRefetch(monitor: ListMonitor<ListEntityType>) { }
func listMonitorWillRefetch(_ monitor: ListMonitor<ListEntityType>) { }
/**
The default implementation does nothing.
*/
func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>) { }
func listMonitorDidRefetch(_ monitor: ListMonitor<ListEntityType>) { }
}
@@ -125,7 +125,7 @@ public protocol ListObjectObserver: ListObserver {
- parameter object: the entity type for the inserted object
- parameter indexPath: the new `NSIndexPath` for the inserted object
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didInsertObject object: ListEntityType, toIndexPath indexPath: NSIndexPath)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didInsertObject object: ListEntityType, toIndexPath indexPath: IndexPath)
/**
Notifies that an object was deleted from the specified `NSIndexPath` in the list
@@ -134,7 +134,7 @@ public protocol ListObjectObserver: ListObserver {
- parameter object: the entity type for the deleted object
- parameter indexPath: the `NSIndexPath` for the deleted object
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didDeleteObject object: ListEntityType, fromIndexPath indexPath: NSIndexPath)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didDeleteObject object: ListEntityType, fromIndexPath indexPath: IndexPath)
/**
Notifies that an object at the specified `NSIndexPath` was updated
@@ -143,7 +143,7 @@ public protocol ListObjectObserver: ListObserver {
- parameter object: the entity type for the updated object
- parameter indexPath: the `NSIndexPath` for the updated object
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didUpdateObject object: ListEntityType, atIndexPath indexPath: NSIndexPath)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didUpdateObject object: ListEntityType, atIndexPath indexPath: IndexPath)
/**
Notifies that an object's index changed
@@ -153,7 +153,7 @@ public protocol ListObjectObserver: ListObserver {
- parameter fromIndexPath: the previous `NSIndexPath` for the moved object
- parameter toIndexPath: the new `NSIndexPath` for the moved object
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didMoveObject object: ListEntityType, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didMoveObject object: ListEntityType, fromIndexPath: IndexPath, toIndexPath: IndexPath)
}
@@ -164,22 +164,22 @@ public extension ListObjectObserver {
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didInsertObject object: ListEntityType, toIndexPath indexPath: NSIndexPath) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didInsertObject object: ListEntityType, toIndexPath indexPath: IndexPath) { }
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didDeleteObject object: ListEntityType, fromIndexPath indexPath: NSIndexPath) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didDeleteObject object: ListEntityType, fromIndexPath indexPath: IndexPath) { }
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didUpdateObject object: ListEntityType, atIndexPath indexPath: NSIndexPath) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didUpdateObject object: ListEntityType, atIndexPath indexPath: IndexPath) { }
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didMoveObject object: ListEntityType, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didMoveObject object: ListEntityType, fromIndexPath: IndexPath, toIndexPath: IndexPath) { }
}
@@ -205,7 +205,7 @@ public protocol ListSectionObserver: ListObjectObserver {
- parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the inserted section
- parameter sectionIndex: the new section index for the new section
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
/**
Notifies that a section was inserted at the specified index
@@ -214,7 +214,7 @@ public protocol ListSectionObserver: ListObjectObserver {
- parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the deleted section
- parameter sectionIndex: the previous section index for the deleted section
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)
}
@@ -225,12 +225,12 @@ public extension ListSectionObserver {
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { }
/**
The default implementation does nothing.
*/
func listMonitor(monitor: ListMonitor<ListEntityType>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { }
func listMonitor(_ monitor: ListMonitor<ListEntityType>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { }
}
#endif
+38 -38
View File
@@ -44,14 +44,14 @@ import CoreData
Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles.
*/
public final class ObjectMonitor<T: NSManagedObject> {
public final class ObjectMonitor<EntityType: NSManagedObject> {
/**
Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted.
*/
public var object: T? {
public var object: EntityType? {
return self.fetchedResultsController.fetchedObjects?.first as? T
return self.fetchedResultsController.fetchedObjects?.first as? EntityType
}
/**
@@ -73,7 +73,7 @@ public final class ObjectMonitor<T: NSManagedObject> {
- parameter observer: an `ObjectObserver` to send change notifications to
*/
public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
public func addObserver<U: ObjectObserver where U.ObjectEntityType == EntityType>(_ observer: U) {
self.unregisterObserver(observer)
self.registerObserver(
@@ -100,7 +100,7 @@ public final class ObjectMonitor<T: NSManagedObject> {
- parameter observer: an `ObjectObserver` to unregister notifications to
*/
public func removeObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
public func removeObserver<U: ObjectObserver where U.ObjectEntityType == EntityType>(_ observer: U) {
self.unregisterObserver(observer)
}
@@ -116,21 +116,21 @@ public final class ObjectMonitor<T: NSManagedObject> {
// MARK: Internal
internal convenience init(dataStack: DataStack, object: T) {
internal convenience init(dataStack: DataStack, object: EntityType) {
self.init(context: dataStack.mainContext, object: object)
}
internal convenience init(unsafeTransaction: UnsafeDataTransaction, object: T) {
internal convenience init(unsafeTransaction: UnsafeDataTransaction, object: EntityType) {
self.init(context: unsafeTransaction.context, object: object)
}
internal func registerObserver<U: AnyObject>(observer: U, willChangeObject: (observer: U, monitor: ObjectMonitor<T>, object: T) -> Void, didDeleteObject: (observer: U, monitor: ObjectMonitor<T>, object: T) -> Void, didUpdateObject: (observer: U, monitor: ObjectMonitor<T>, object: T, changedPersistentKeys: Set<String>) -> Void) {
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) {
CoreStore.assert(
NSThread.isMainThread(),
"Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread."
Thread.isMainThread,
"Attempted to add an observer of type \(cs_typeName(observer as AnyObject)) outside the main thread."
)
self.registerChangeNotification(
&self.willChangeObjectKey,
@@ -170,7 +170,7 @@ public final class ObjectMonitor<T: NSManagedObject> {
}
let previousCommitedAttributes = self.lastCommittedAttributes
let currentCommitedAttributes = object.committedValuesForKeys(nil) as! [String: NSObject]
let currentCommitedAttributes = object.committedValues(forKeys: nil) as! [String: NSObject]
var changedKeys = Set<String>()
for key in currentCommitedAttributes.keys {
@@ -192,10 +192,10 @@ public final class ObjectMonitor<T: NSManagedObject> {
)
}
internal func unregisterObserver(observer: AnyObject) {
internal func unregisterObserver(_ observer: AnyObject) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to remove an observer of type \(cs_typeName(observer)) outside the main thread."
)
@@ -207,7 +207,7 @@ public final class ObjectMonitor<T: NSManagedObject> {
internal func upcast() -> ObjectMonitor<NSManagedObject> {
return unsafeBitCast(self, ObjectMonitor<NSManagedObject>.self)
return unsafeBitCast(self, to: ObjectMonitor<NSManagedObject>.self)
}
deinit {
@@ -219,19 +219,19 @@ public final class ObjectMonitor<T: NSManagedObject> {
// MARK: Private
private let fetchedResultsController: CoreStoreFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<EntityType>
private var lastCommittedAttributes = [String: NSObject]()
private var willChangeObjectKey: Void?
private var didDeleteObjectKey: Void?
private var didUpdateObjectKey: Void?
private init(context: NSManagedObjectContext, object: T) {
private init(context: NSManagedObjectContext, object: EntityType) {
let fetchRequest = CoreStoreFetchRequest()
let fetchRequest = CoreStoreFetchRequest<EntityType>()
fetchRequest.entity = object.entity
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.resultType = .managedObjectResultType
fetchRequest.sortDescriptors = []
fetchRequest.includesPendingChanges = false
fetchRequest.shouldRefreshRefetchedObjects = true
@@ -239,11 +239,11 @@ public final class ObjectMonitor<T: NSManagedObject> {
let objectID = object.objectID
let fetchedResultsController = CoreStoreFetchedResultsController(
context: context,
fetchRequest: fetchRequest,
fetchRequest: fetchRequest.dynamicCast(),
applyFetchClauses: Where("SELF", isEqualTo: objectID).applyToFetchRequest
)
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate()
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate<EntityType>()
self.fetchedResultsController = fetchedResultsController
self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate
@@ -252,10 +252,10 @@ public final class ObjectMonitor<T: NSManagedObject> {
fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController
try! fetchedResultsController.performFetchFromSpecifiedStores()
self.lastCommittedAttributes = (self.object?.committedValuesForKeys(nil) as? [String: NSObject]) ?? [:]
self.lastCommittedAttributes = (self.object?.committedValues(forKeys: nil) as? [String: NSObject]) ?? [:]
}
private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>) -> Void) {
private func registerChangeNotification(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<EntityType>) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -275,7 +275,7 @@ public final class ObjectMonitor<T: NSManagedObject> {
)
}
private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>, object: T) -> Void) {
private func registerObjectNotification(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<EntityType>, object: EntityType) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -284,8 +284,8 @@ public final class ObjectMonitor<T: NSManagedObject> {
closure: { [weak self] (note) -> Void in
guard let `self` = self,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T else {
let userInfo = (note as NSNotification).userInfo,
let object = userInfo[UserInfoKeyObject] as? EntityType else {
return
}
@@ -320,30 +320,30 @@ extension ObjectMonitor: FetchedResultsControllerHandler {
// MARK: FetchedResultsControllerHandler
internal func controllerWillChangeContent(controller: NSFetchedResultsController) {
internal func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorWillChangeObjectNotification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: ObjectMonitorWillChangeObjectNotification),
object: self
)
}
internal func controllerDidChangeContent(controller: NSFetchedResultsController) { }
internal func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { }
internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeObject anObject: AnyObject, atIndexPath indexPath: IndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidDeleteObjectNotification,
case .delete:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ObjectMonitorDidDeleteObjectNotification),
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
case .Update:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidUpdateObjectNotification,
case .update:
NotificationCenter.default.post(
name: Notification.Name(rawValue: ObjectMonitorDidUpdateObjectNotification),
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
@@ -353,9 +353,9 @@ extension ObjectMonitor: FetchedResultsControllerHandler {
}
}
internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { }
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { }
internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
internal func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, sectionIndexTitleForSectionName sectionName: String?) -> String? {
return sectionName
}
+6 -6
View File
@@ -51,7 +51,7 @@ public protocol ObjectObserver: class {
- parameter monitor: the `ObjectMonitor` monitoring the object being observed
- parameter object: the `NSManagedObject` instance being observed
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, willUpdateObject object: ObjectEntityType)
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, willUpdateObject object: ObjectEntityType)
/**
Handles processing right after a change to the observed `object` occurs
@@ -60,7 +60,7 @@ public protocol ObjectObserver: class {
- parameter object: the `NSManagedObject` instance being observed
- parameter changedPersistentKeys: a `Set` of key paths for the attributes that were changed. Note that `changedPersistentKeys` only contains keys for attributes/relationships present in the persistent store, thus transient properties will not be reported.
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didUpdateObject object: ObjectEntityType, changedPersistentKeys: Set<KeyPath>)
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, didUpdateObject object: ObjectEntityType, changedPersistentKeys: Set<KeyPath>)
/**
Handles processing right after `object` is deleted
@@ -68,7 +68,7 @@ public protocol ObjectObserver: class {
- parameter monitor: the `ObjectMonitor` monitoring the object being observed
- parameter object: the `NSManagedObject` instance being observed
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType)
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType)
}
@@ -79,17 +79,17 @@ public extension ObjectObserver {
/**
The default implementation does nothing.
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, willUpdateObject object: ObjectEntityType) { }
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, willUpdateObject object: ObjectEntityType) { }
/**
The default implementation does nothing.
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didUpdateObject object: ObjectEntityType, changedPersistentKeys: Set<KeyPath>) { }
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, didUpdateObject object: ObjectEntityType, changedPersistentKeys: Set<KeyPath>) { }
/**
The default implementation does nothing.
*/
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType) { }
func objectMonitor(_ monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType) { }
}
#endif
@@ -43,7 +43,7 @@ public extension UnsafeDataTransaction {
- returns: a `ObjectMonitor` that monitors changes to `object`
*/
@warn_unused_result
public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {
public func monitorObject<T: NSManagedObject>(_ object: T) -> ObjectMonitor<T> {
return ObjectMonitor(
unsafeTransaction: self,
@@ -59,7 +59,7 @@ public extension UnsafeDataTransaction {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.monitorList(from, fetchClauses)
}
@@ -72,7 +72,7 @@ public extension UnsafeDataTransaction {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public func monitorList<T: NSManagedObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
CoreStore.assert(
fetchClauses.filter { $0 is OrderBy }.count > 0,
@@ -97,7 +97,7 @@ public extension UnsafeDataTransaction {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
public func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) {
self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses)
}
@@ -109,7 +109,7 @@ public extension UnsafeDataTransaction {
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
public func monitorList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) {
CoreStore.assert(
fetchClauses.filter { $0 is OrderBy }.count > 0,
@@ -137,7 +137,7 @@ public extension UnsafeDataTransaction {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
public func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> {
return self.monitorSectionedList(from, sectionBy, fetchClauses)
}
@@ -151,7 +151,7 @@ public extension UnsafeDataTransaction {
- returns: a `ListMonitor` instance that monitors changes to the list
*/
@warn_unused_result
public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
public func monitorSectionedList<T: NSManagedObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> {
CoreStore.assert(
fetchClauses.filter { $0 is OrderBy }.count > 0,
@@ -177,7 +177,7 @@ public extension UnsafeDataTransaction {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) {
self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses)
}
@@ -190,7 +190,7 @@ public extension UnsafeDataTransaction {
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
public func monitorSectionedList<T: NSManagedObject>(createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) {
CoreStore.assert(
fetchClauses.filter { $0 is OrderBy }.count > 0,
+12 -71
View File
@@ -53,7 +53,7 @@ public extension CoreStore {
/**
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from `defaultStack`'s model.
*/
public static func entityDescriptionForType(type: NSManagedObject.Type) -> NSEntityDescription? {
public static func entityDescriptionForType(_ type: NSManagedObject.Type) -> NSEntityDescription? {
return self.defaultStack.entityDescriptionForType(type)
}
@@ -66,22 +66,24 @@ public extension CoreStore {
- returns: the local SQLite storage added to the `defaultStack`
*/
@discardableResult
public static func addStorageAndWait() throws -> SQLiteStore {
return try self.defaultStack.addStorageAndWait(SQLiteStore)
return try self.defaultStack.addStorageAndWait(SQLiteStore.self)
}
/**
Creates a `StorageInterface` of the specified store type with default values and adds it to the `defaultStack`. This method blocks until completion.
```
try CoreStore.addStorageAndWait(InMemoryStore)
try CoreStore.addStorageAndWait(InMemoryStore.self)
```
- parameter storeType: the `StorageInterface` type
- throws: a `CoreStoreError` value indicating the failure
- returns: the `StorageInterface` added to the `defaultStack`
*/
public static func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(storeType: T.Type) throws -> T {
@discardableResult
public static func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type) throws -> T {
return try self.defaultStack.addStorageAndWait(storeType.init())
}
@@ -96,7 +98,7 @@ public extension CoreStore {
- throws: a `CoreStoreError` value indicating the failure
- returns: the `StorageInterface` added to the `defaultStack`
*/
public static func addStorageAndWait<T: StorageInterface>(storage: T) throws -> T {
public static func addStorageAndWait<T: StorageInterface>(_ storage: T) throws -> T {
return try self.defaultStack.addStorageAndWait(storage)
}
@@ -104,14 +106,14 @@ public extension CoreStore {
/**
Creates a `LocalStorageface` of the specified store type with default values and adds it to the `defaultStack`. This method blocks until completion.
```
try CoreStore.addStorageAndWait(SQLiteStore)
try CoreStore.addStorageAndWait(SQLiteStore.self)
```
- parameter storeType: the `LocalStorageface` type
- throws: a `CoreStoreError` value indicating the failure
- returns: the local storage added to the `defaultStack`
*/
public static func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(storageType: T.Type) throws -> T {
public static func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(_ storageType: T.Type) throws -> T {
return try self.defaultStack.addStorageAndWait(storageType.init())
}
@@ -126,7 +128,7 @@ public extension CoreStore {
- throws: a `CoreStoreError` value indicating the failure
- returns: the local storage added to the `defaultStack`. Note that this 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.
*/
public static func addStorageAndWait<T: LocalStorage>(storage: T) throws -> T {
public static func addStorageAndWait<T: LocalStorage>(_ storage: T) throws -> T {
return try self.defaultStack.addStorageAndWait(storage)
}
@@ -140,7 +142,7 @@ public extension CoreStore {
ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername",
ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0",
configuration: "Config1",
cloudStorageOptions: .RecreateLocalStoreOnModelMismatch
cloudStorageOptions: .recreateLocalStoreOnModelMismatch
) else {
// iCloud is not available on the device
return
@@ -152,69 +154,8 @@ public extension CoreStore {
- throws: a `CoreStoreError` value indicating the failure
- returns: the cloud storage added to the stack. Note that this 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 static func addStorageAndWait<T: CloudStorage>(storage: T) throws -> T {
public static func addStorageAndWait<T: CloudStorage>(_ storage: T) throws -> T {
return try self.defaultStack.addStorageAndWait(storage)
}
// MARK: Deprecated
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `InMemoryStore` instance.
```
try CoreStore.addStorage(InMemoryStore(configuration: configuration))
```
*/
@available(*, deprecated=2.0.0, obsoleted=2.0.0, message="Use addStorageAndWait(_:) by passing an InMemoryStore instance.")
public static func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore {
return try self.defaultStack.addInMemoryStoreAndWait(configuration: configuration)
}
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `LegacySQLiteStore` instance.
```
try CoreStore.addStorage(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
localStorageOptions: .RecreateStoreOnModelMismatch
)
)
```
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addStorageAndWait(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
return try self.defaultStack.addSQLiteStoreAndWait(
fileName: fileName,
configuration: configuration,
resetStoreOnModelMismatch: resetStoreOnModelMismatch
)
}
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `LegacySQLiteStore` instance.
```
try CoreStore.addStorage(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
localStorageOptions: .RecreateStoreOnModelMismatch
)
)
```
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addStorageAndWait(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public static func addSQLiteStoreAndWait(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
return try self.defaultStack.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: resetStoreOnModelMismatch
)
}
}
+65 -143
View File
@@ -44,7 +44,7 @@ public final class DataStack {
- parameter bundle: an optional bundle to load models from. If not specified, the main bundle will be used.
- parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
*/
public convenience init(modelName: String = DataStack.applicationName, bundle: NSBundle = NSBundle.mainBundle(), migrationChain: MigrationChain = nil) {
public convenience init(modelName: String = DataStack.applicationName, bundle: Bundle = Bundle.main, migrationChain: MigrationChain = nil) {
let model = NSManagedObjectModel.fromBundle(
bundle,
@@ -64,7 +64,7 @@ public final class DataStack {
CoreStore.assert(
migrationChain.valid,
"Invalid migration chain passed to the \(cs_typeName(DataStack)). Check that the model versions' order is correct and that no repetitions or ambiguities exist."
"Invalid migration chain passed to the \(cs_typeName(DataStack.self)). Check that the model versions' order is correct and that no repetitions or ambiguities exist."
)
self.coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
@@ -95,20 +95,20 @@ public final class DataStack {
/**
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass.
*/
public func entityDescriptionForType(type: NSManagedObject.Type) -> NSEntityDescription? {
public func entityDescriptionForType(_ type: NSManagedObject.Type) -> NSEntityDescription? {
return NSEntityDescription.entityForName(
self.model.entityNameForClass(type),
inManagedObjectContext: self.mainContext
return NSEntityDescription.entity(
forEntityName: self.model.entityNameForClass(type),
in: self.mainContext
)
}
/**
Returns the `NSManagedObjectID` for the specified object URI if it exists in the persistent store.
*/
public func objectIDForURIRepresentation(url: NSURL) -> NSManagedObjectID? {
public func objectIDForURIRepresentation(_ url: URL) -> NSManagedObjectID? {
return self.coordinator.managedObjectIDForURIRepresentation(url)
return self.coordinator.managedObjectID(forURIRepresentation: url)
}
/**
@@ -122,20 +122,20 @@ public final class DataStack {
*/
public func addStorageAndWait() throws -> SQLiteStore {
return try self.addStorageAndWait(SQLiteStore)
return try self.addStorageAndWait(SQLiteStore.self)
}
/**
Creates a `StorageInterface` of the specified store type with default values and adds it to the stack. This method blocks until completion.
```
try dataStack.addStorageAndWait(InMemoryStore)
try dataStack.addStorageAndWait(InMemoryStore.self)
```
- parameter storeType: the `StorageInterface` type
- throws: a `CoreStoreError` value indicating the failure
- returns: the `StorageInterface` added to the stack
*/
public func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(storeType: T.Type) throws -> T {
public func addStorageAndWait<T: StorageInterface where T: DefaultInitializableStore>(_ storeType: T.Type) throws -> T {
return try self.addStorageAndWait(storeType.init())
}
@@ -150,7 +150,7 @@ public final class DataStack {
- throws: a `CoreStoreError` value indicating the failure
- returns: the `StorageInterface` added to the stack
*/
public func addStorageAndWait<T: StorageInterface>(storage: T) throws -> T {
public func addStorageAndWait<T: StorageInterface>(_ storage: T) throws -> T {
do {
@@ -160,8 +160,7 @@ public final class DataStack {
return storage
}
try self.createPersistentStoreFromStorage(
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: nil,
finalStoreOptions: storage.storeOptions
@@ -183,14 +182,14 @@ public final class DataStack {
/**
Creates a `LocalStorageface` of the specified store type with default values and adds it to the stack. This method blocks until completion.
```
try dataStack.addStorageAndWait(SQLiteStore)
try dataStack.addStorageAndWait(SQLiteStore.self)
```
- parameter storeType: the `LocalStorageface` type
- throws: a `CoreStoreError` value indicating the failure
- returns: the local storage added to the stack
*/
public func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(storageType: T.Type) throws -> T {
public func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(_ storageType: T.Type) throws -> T {
return try self.addStorageAndWait(storageType.init())
}
@@ -205,13 +204,13 @@ public final class DataStack {
- throws: a `CoreStoreError` value indicating the failure
- returns: the local storage added to the stack. Note that this 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.
*/
public func addStorageAndWait<T: LocalStorage>(storage: T) throws -> T {
public func addStorageAndWait<T: LocalStorage>(_ storage: T) throws -> T {
return try self.coordinator.performSynchronously {
let fileURL = storage.fileURL
CoreStore.assert(
fileURL.fileURL,
fileURL.isFileURL,
"The specified store URL for the \"\(cs_typeName(storage))\" is invalid: \"\(fileURL)\""
)
@@ -220,7 +219,7 @@ public final class DataStack {
return storage
}
if let persistentStore = self.coordinator.persistentStoreForURL(fileURL) {
if let persistentStore = self.coordinator.persistentStore(for: fileURL as URL) {
if let existingStorage = persistentStore.storageInterface as? T
where storage.matchesPersistentStore(persistentStore) {
@@ -228,10 +227,10 @@ public final class DataStack {
return existingStorage
}
let error = CoreStoreError.DifferentStorageExistsAtURL(existingPersistentStoreURL: fileURL)
let error = CoreStoreError.differentStorageExistsAtURL(existingPersistentStoreURL: fileURL)
CoreStore.log(
error,
"Failed to add \(cs_typeName(storage)) at \"\(fileURL)\" because a different \(cs_typeName(NSPersistentStore)) 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."
)
throw error
}
@@ -239,33 +238,32 @@ public final class DataStack {
do {
var localStorageOptions = storage.localStorageOptions
localStorageOptions.remove(.RecreateStoreOnModelMismatch)
localStorageOptions.remove(.recreateStoreOnModelMismatch)
let storeOptions = storage.storeOptionsForOptions(localStorageOptions)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
try FileManager.default.createDirectory(
at: try fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try self.createPersistentStoreFromStorage(
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: fileURL,
finalStoreOptions: storeOptions
)
return storage
}
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.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: fileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: fileURL,
options: storeOptions
)
try _ = self.model[metadata].flatMap(storage.eraseStorageAndWait)
try self.createPersistentStoreFromStorage(
_ = try self.model[metadata].flatMap(storage.eraseStorageAndWait)
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: fileURL,
finalStoreOptions: storeOptions
@@ -294,7 +292,7 @@ public final class DataStack {
ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername",
ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0",
configuration: "Config1",
cloudStorageOptions: .RecreateLocalStoreOnModelMismatch
cloudStorageOptions: .recreateLocalStoreOnModelMismatch
) else {
// iCloud is not available on the device
return
@@ -306,7 +304,7 @@ public final class DataStack {
- throws: a `CoreStoreError` value indicating the failure
- returns: the cloud storage added to the stack. Note that this 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 addStorageAndWait<T: CloudStorage>(storage: T) throws -> T {
public func addStorageAndWait<T: CloudStorage>(_ storage: T) throws -> T {
return try self.coordinator.performSynchronously {
@@ -316,7 +314,7 @@ public final class DataStack {
}
let cacheFileURL = storage.cacheFileURL
if let persistentStore = self.coordinator.persistentStoreForURL(cacheFileURL) {
if let persistentStore = self.coordinator.persistentStore(for: cacheFileURL as URL) {
if let existingStorage = persistentStore.storageInterface as? T
where storage.matchesPersistentStore(persistentStore) {
@@ -324,10 +322,10 @@ public final class DataStack {
return existingStorage
}
let error = CoreStoreError.DifferentStorageExistsAtURL(existingPersistentStoreURL: cacheFileURL)
let error = CoreStoreError.differentStorageExistsAtURL(existingPersistentStoreURL: cacheFileURL)
CoreStore.log(
error,
"Failed to add \(cs_typeName(storage)) at \"\(cacheFileURL)\" because a different \(cs_typeName(NSPersistentStore)) 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."
)
throw error
}
@@ -335,33 +333,32 @@ public final class DataStack {
do {
var cloudStorageOptions = storage.cloudStorageOptions
cloudStorageOptions.remove(.RecreateLocalStoreOnModelMismatch)
cloudStorageOptions.remove(.recreateLocalStoreOnModelMismatch)
let storeOptions = storage.storeOptionsForOptions(cloudStorageOptions)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(
cacheFileURL.URLByDeletingLastPathComponent!,
try FileManager.default.createDirectory(
at: try cacheFileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try self.createPersistentStoreFromStorage(
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: cacheFileURL,
finalStoreOptions: storeOptions
)
return storage
}
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.metadataForPersistentStoreOfType(
storage.dynamicType.storeType,
URL: cacheFileURL,
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: storage.dynamicType.storeType,
at: cacheFileURL,
options: storeOptions
)
try _ = self.model[metadata].flatMap(storage.eraseStorageAndWait)
try self.createPersistentStoreFromStorage(
_ = try self.model[metadata].flatMap(storage.eraseStorageAndWait)
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: cacheFileURL,
finalStoreOptions: storeOptions
@@ -384,7 +381,7 @@ public final class DataStack {
// MARK: Internal
internal static let applicationName = (NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData"
internal static let applicationName = (Bundle.main.objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData"
internal let coordinator: NSPersistentStoreCoordinator
internal let rootSavingContext: NSManagedObjectContext
@@ -393,39 +390,32 @@ public final class DataStack {
internal let migrationChain: MigrationChain
internal let childTransactionQueue: GCDQueue = .createSerial("com.coreStore.dataStack.childTransactionQueue")
internal let storeMetadataUpdateQueue = GCDQueue.createConcurrent("com.coreStore.persistentStoreBarrierQueue")
internal let migrationQueue: NSOperationQueue = {
internal let migrationQueue: OperationQueue = {
let migrationQueue = NSOperationQueue()
let migrationQueue = OperationQueue()
migrationQueue.maxConcurrentOperationCount = 1
migrationQueue.name = "com.coreStore.migrationOperationQueue"
#if USE_FRAMEWORKS
migrationQueue.qualityOfService = .Utility
migrationQueue.underlyingQueue = dispatch_queue_create("com.coreStore.migrationQueue", DISPATCH_QUEUE_SERIAL)
#else
if #available(iOS 8.0, *) {
migrationQueue.qualityOfService = .Utility
migrationQueue.underlyingQueue = dispatch_queue_create("com.coreStore.migrationQueue", DISPATCH_QUEUE_SERIAL)
}
#endif
migrationQueue.qualityOfService = .utility
migrationQueue.underlyingQueue = DispatchQueue(
label: "com.coreStore.migrationQueue",
attributes: .serial
)
return migrationQueue
}()
internal func persistentStoreForStorage(storage: StorageInterface) -> NSPersistentStore? {
internal func persistentStoreForStorage(_ storage: StorageInterface) -> NSPersistentStore? {
return self.coordinator.persistentStores
.filter { $0.storageInterface === storage }
.first
}
internal func entityNameForEntityClass(entityClass: AnyClass) -> String? {
internal func entityNameForEntityClass(_ entityClass: AnyClass) -> String? {
return self.model.entityNameForClass(entityClass)
}
internal func persistentStoresForEntityClass(entityClass: AnyClass) -> [NSPersistentStore]? {
internal func persistentStoresForEntityClass(_ entityClass: AnyClass) -> [NSPersistentStore]? {
var returnValue: [NSPersistentStore]? = nil
self.storeMetadataUpdateQueue.barrierSync {
@@ -438,7 +428,7 @@ public final class DataStack {
return returnValue
}
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)
self.storeMetadataUpdateQueue.barrierSync {
@@ -472,12 +462,12 @@ public final class DataStack {
return returnValue
}
internal func createPersistentStoreFromStorage(storage: StorageInterface, finalURL: NSURL?, finalStoreOptions: [String: AnyObject]?) throws -> NSPersistentStore {
internal func createPersistentStoreFromStorage(_ storage: StorageInterface, finalURL: URL?, finalStoreOptions: [String: AnyObject]?) throws -> NSPersistentStore {
let persistentStore = try self.coordinator.addPersistentStoreWithType(
storage.dynamicType.storeType,
configuration: storage.configuration,
URL: finalURL,
let persistentStore = try self.coordinator.addPersistentStore(
ofType: storage.dynamicType.storeType,
configurationName: storage.configuration,
at: finalURL,
options: finalStoreOptions
)
persistentStore.storageInterface = storage
@@ -486,9 +476,9 @@ public final class DataStack {
let configurationName = persistentStore.configurationName
self.configurationStoreMapping[configurationName] = persistentStore
for entityDescription in (self.coordinator.managedObjectModel.entitiesForConfiguration(configurationName) ?? []) {
for entityDescription in (self.coordinator.managedObjectModel.entities(forConfigurationName: configurationName) ?? []) {
let managedObjectClassName = entityDescription.managedObjectClassName
let managedObjectClassName = entityDescription.managedObjectClassName!
CoreStore.assert(
NSClassFromString(managedObjectClassName) != nil,
"The class \(cs_typeName(managedObjectClassName)) for the entity \(cs_typeName(entityDescription.name)) does not exist. Check if the subclass type and module name are properly configured."
@@ -520,79 +510,11 @@ public final class DataStack {
coordinator.persistentStores.forEach {
_ = try? coordinator.removePersistentStore($0)
_ = try? coordinator.remove($0)
}
}
}
}
// MARK: Deprecated
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `InMemoryStore` instance.
```
try dataStack.addStorage(InMemoryStore(configuration: configuration))
```
*/
@available(*, deprecated=2.0.0, message="Use addStorageAndWait(_:) by passing an InMemoryStore instance.")
public func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore {
let storage = try self.addStorageAndWait(InMemoryStore(configuration: configuration))
return self.persistentStoreForStorage(storage)!
}
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `LegacySQLiteStore` instance.
```
try dataStack.addStorage(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
localStorageOptions: .RecreateStoreOnModelMismatch
)
)
```
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addStorageAndWait(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
let storage = try self.addStorageAndWait(
LegacySQLiteStore(
fileName: fileName,
configuration: configuration,
localStorageOptions: resetStoreOnModelMismatch ? .RecreateStoreOnModelMismatch : .None
)
)
return self.persistentStoreForStorage(storage)!
}
/**
Deprecated. Use `addStorageAndWait(_:)` by passing a `LegacySQLiteStore` instance.
```
try dataStack.addStorage(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
localStorageOptions: .RecreateStoreOnModelMismatch
)
)
```
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was using this method prior to 2.0.0, make sure to use `LegacySQLiteStore`.
*/
@available(*, deprecated=2.0.0, message="Use addStorageAndWait(_:) by passing a LegacySQLiteStore instance. Warning: The default SQLite file location for the LegacySQLiteStore and SQLiteStore are different. If the app was using this method prior to 2.0.0, make sure to use LegacySQLiteStore.")
public func addSQLiteStoreAndWait(fileURL fileURL: NSURL = LegacySQLiteStore.defaultFileURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
let storage = try self.addStorageAndWait(
LegacySQLiteStore(
fileURL: fileURL,
configuration: configuration,
localStorageOptions: resetStoreOnModelMismatch ? .RecreateStoreOnModelMismatch : .None
)
)
return self.persistentStoreForStorage(storage)!
}
}
@@ -45,7 +45,7 @@ public class ICloudStore: CloudStorage {
ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername",
ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0",
configuration: "Config1",
cloudStorageOptions: .RecreateLocalStoreOnModelMismatch
cloudStorageOptions: .recreateLocalStoreOnModelMismatch
) else {
// iCloud is not available on the device
return
@@ -73,7 +73,7 @@ public class ICloudStore: CloudStorage {
"The ubiquitousContentName cannot be empty."
)
CoreStore.assert(
!ubiquitousContentName.containsString("."),
!ubiquitousContentName.contains("."),
"The ubiquitousContentName cannot contain periods."
)
CoreStore.assert(
@@ -85,8 +85,8 @@ public class ICloudStore: CloudStorage {
"The ubiquitousPeerToken should not be empty if provided."
)
let fileManager = NSFileManager.defaultManager()
guard let cacheFileURL = fileManager.URLForUbiquityContainerIdentifier(ubiquitousContainerID) else {
let fileManager = FileManager.default
guard let cacheFileURL = fileManager.urlForUbiquityContainerIdentifier(ubiquitousContainerID) else {
return nil
}
@@ -110,10 +110,10 @@ public class ICloudStore: CloudStorage {
- parameter observer: the observer to start sending ubiquitous notifications to
*/
public func addObserver<T: ICloudStoreObserver>(observer: T) {
public func addObserver<T: ICloudStoreObserver>(_ observer: T) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread."
)
@@ -198,10 +198,10 @@ public class ICloudStore: CloudStorage {
- parameter observer: the observer to stop sending ubiquitous notifications to
*/
public func removeObserver(observer: ICloudStoreObserver) {
public func removeObserver(_ observer: ICloudStoreObserver) {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to remove an observer of type \(cs_typeName(observer)) outside the main thread."
)
let nilValue: AnyObject? = nil
@@ -271,7 +271,7 @@ public class ICloudStore: CloudStorage {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didAddToDataStack(dataStack: DataStack) {
public func didAddToDataStack(_ dataStack: DataStack) {
self.didRemoveFromDataStack(dataStack)
@@ -280,38 +280,38 @@ public class ICloudStore: CloudStorage {
cs_setAssociatedRetainedObject(
NotificationObserver(
notificationName: NSPersistentStoreCoordinatorStoresWillChangeNotification,
notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresWillChange.rawValue,
object: coordinator,
closure: { [weak self, weak dataStack] (note) -> Void in
guard let `self` = self,
let dataStack = dataStack,
let userInfo = note.userInfo,
let userInfo = (note as NSNotification).userInfo,
let transitionType = userInfo[NSPersistentStoreUbiquitousTransitionTypeKey] as? NSNumber else {
return
}
let notification: String
switch NSPersistentStoreUbiquitousTransitionType(rawValue: transitionType.unsignedIntegerValue) {
switch NSPersistentStoreUbiquitousTransitionType(rawValue: transitionType.uintValue) {
case .InitialImportCompleted?:
case .initialImportCompleted?:
notification = ICloudUbiquitousStoreWillFinishInitialImportNotification
case .AccountAdded?:
case .accountAdded?:
notification = ICloudUbiquitousStoreWillAddAccountNotification
case .AccountRemoved?:
case .accountRemoved?:
notification = ICloudUbiquitousStoreWillRemoveAccountNotification
case .ContentRemoved?:
case .contentRemoved?:
notification = ICloudUbiquitousStoreWillRemoveContentNotification
default:
return
}
NSNotificationCenter.defaultCenter().postNotificationName(
notification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: notification),
object: self,
userInfo: [UserInfoKeyDataStack: dataStack]
)
@@ -322,38 +322,38 @@ public class ICloudStore: CloudStorage {
)
cs_setAssociatedRetainedObject(
NotificationObserver(
notificationName: NSPersistentStoreCoordinatorStoresDidChangeNotification,
notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresDidChange.rawValue,
object: coordinator,
closure: { [weak self, weak dataStack] (note) -> Void in
guard let `self` = self,
let dataStack = dataStack,
let userInfo = note.userInfo,
let userInfo = (note as NSNotification).userInfo,
let transitionType = userInfo[NSPersistentStoreUbiquitousTransitionTypeKey] as? NSNumber else {
return
}
let notification: String
switch NSPersistentStoreUbiquitousTransitionType(rawValue: transitionType.unsignedIntegerValue) {
switch NSPersistentStoreUbiquitousTransitionType(rawValue: transitionType.uintValue) {
case .InitialImportCompleted?:
case .initialImportCompleted?:
notification = ICloudUbiquitousStoreDidFinishInitialImportNotification
case .AccountAdded?:
case .accountAdded?:
notification = ICloudUbiquitousStoreDidAddAccountNotification
case .AccountRemoved?:
case .accountRemoved?:
notification = ICloudUbiquitousStoreDidRemoveAccountNotification
case .ContentRemoved?:
case .contentRemoved?:
notification = ICloudUbiquitousStoreDidRemoveContentNotification
default:
return
}
NSNotificationCenter.defaultCenter().postNotificationName(
notification,
NotificationCenter.default.post(
name: Notification.Name(rawValue: notification),
object: self,
userInfo: [UserInfoKeyDataStack: dataStack]
)
@@ -367,7 +367,7 @@ public class ICloudStore: CloudStorage {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didRemoveFromDataStack(dataStack: DataStack) {
public func didRemoveFromDataStack(_ dataStack: DataStack) {
let coordinator = dataStack.coordinator
let nilValue: AnyObject? = nil
@@ -391,7 +391,7 @@ public class ICloudStore: CloudStorage {
/**
The `NSURL` that points to the ubiquity container file
*/
public let cacheFileURL: NSURL
public let cacheFileURL: URL
/**
Options that tell the `DataStack` how to setup the persistent store
@@ -401,20 +401,20 @@ public class ICloudStore: CloudStorage {
/**
The options dictionary for the specified `CloudStorageOptions`
*/
public func storeOptionsForOptions(options: CloudStorageOptions) -> [String: AnyObject]? {
public func storeOptionsForOptions(_ options: CloudStorageOptions) -> [String: AnyObject]? {
if options == .None {
if options == .none {
return self.storeOptions
}
var storeOptions = self.storeOptions ?? [:]
if options.contains(.AllowSynchronousLightweightMigration) {
if options.contains(.allowSynchronousLightweightMigration) {
storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
storeOptions[NSInferMappingModelAutomaticallyOption] = true
}
if options.contains(.RecreateLocalStoreOnModelMismatch) {
if options.contains(.recreateLocalStoreOnModelMismatch) {
storeOptions[NSPersistentStoreRebuildFromUbiquitousContentOption] = true
}
@@ -424,7 +424,7 @@ public class ICloudStore: CloudStorage {
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
public func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws {
public func eraseStorageAndWait(soureModel: NSManagedObjectModel) throws {
// TODO: check if attached to persistent store
@@ -436,18 +436,18 @@ public class ICloudStore: CloudStorage {
NSSQLitePragmasOption: ["journal_mode": "DELETE"],
NSPersistentStoreRemoveUbiquitousMetadataOption: true
]
let store = try journalUpdatingCoordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: cacheFileURL,
let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType,
configurationName: self.configuration,
at: cacheFileURL,
options: options
)
try journalUpdatingCoordinator.removePersistentStore(store)
try NSPersistentStoreCoordinator.removeUbiquitousContentAndPersistentStoreAtURL(
cacheFileURL,
try journalUpdatingCoordinator.remove(store)
try NSPersistentStoreCoordinator.removeUbiquitousContentAndPersistentStore(
at: cacheFileURL,
options: options
)
try NSFileManager.defaultManager().removeItemAtURL(cacheFileURL)
try FileManager.default.removeItem(at: cacheFileURL)
}
}
@@ -471,7 +471,7 @@ public class ICloudStore: CloudStorage {
private weak var dataStack: DataStack?
private func registerNotification<T: ICloudStoreObserver>(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: T, callback: (observer: T, storage: ICloudStore, dataStack: DataStack) -> Void) {
private func registerNotification<T: ICloudStoreObserver>(_ notificationKey: UnsafePointer<Void>, name: String, toObserver observer: T, callback: (observer: T, storage: ICloudStore, dataStack: DataStack) -> Void) {
cs_setAssociatedRetainedObject(
NotificationObserver(
@@ -481,7 +481,7 @@ public class ICloudStore: CloudStorage {
guard let `self` = self,
let observer = observer,
let dataStack = note.userInfo?[UserInfoKeyDataStack] as? DataStack
let dataStack = (note as NSNotification).userInfo?[UserInfoKeyDataStack] as? DataStack
where self.dataStack === dataStack else {
return
@@ -45,7 +45,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that the initial ubiquitous store import completed
@@ -53,7 +53,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account will be added to the coordinator
@@ -61,7 +61,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillAddAccount(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreWillAddAccount(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account was added to the coordinator
@@ -69,7 +69,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidAddAccount(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreDidAddAccount(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account will be removed from the coordinator
@@ -77,7 +77,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillRemoveAccount(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreWillRemoveAccount(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account was removed from the coordinator
@@ -85,7 +85,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidRemoveAccount(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreDidRemoveAccount(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that iCloud contents will be deleted
@@ -93,7 +93,7 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillRemoveContent(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreWillRemoveContent(storage: ICloudStore, dataStack: DataStack)
/**
Notifies that iCloud contents were deleted
@@ -101,26 +101,26 @@ public protocol ICloudStoreObserver: class {
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidRemoveContent(storage storage: ICloudStore, dataStack: DataStack)
func iCloudStoreDidRemoveContent(storage: ICloudStore, dataStack: DataStack)
}
public extension ICloudStoreObserver {
public func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillAddAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillAddAccount(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidAddAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidAddAccount(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveAccount(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveAccount(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveContent(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveContent(storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveContent(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveContent(storage: ICloudStore, dataStack: DataStack) {}
}
#endif
@@ -74,7 +74,7 @@ public final class InMemoryStore: StorageInterface, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didAddToDataStack(dataStack: DataStack) {
public func didAddToDataStack(_ dataStack: DataStack) {
self.dataStack = dataStack
}
@@ -82,7 +82,7 @@ public final class InMemoryStore: StorageInterface, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didRemoveFromDataStack(dataStack: DataStack) {
public func didRemoveFromDataStack(_ dataStack: DataStack) {
self.dataStack = nil
}
@@ -44,7 +44,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models for migration.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileURL: NSURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
public init(fileURL: URL, configuration: String? = nil, mappingModelBundles: [Bundle] = Bundle.allBundles, localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = fileURL
self.configuration = configuration
@@ -61,9 +61,9 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models for migration.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
public init(fileName: String, configuration: String? = nil, mappingModelBundles: [Bundle] = Bundle.allBundles, localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = LegacySQLiteStore.defaultRootDirectory.URLByAppendingPathComponent(
self.fileURL = try! LegacySQLiteStore.defaultRootDirectory.appendingPathComponent(
fileName,
isDirectory: false
)
@@ -84,7 +84,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
self.fileURL = LegacySQLiteStore.defaultFileURL
self.configuration = nil
self.mappingModelBundles = NSBundle.allBundles()
self.mappingModelBundles = Bundle.allBundles
self.localStorageOptions = nil
}
@@ -99,15 +99,15 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
The options dictionary for the specified `LocalStorageOptions`
*/
public func storeOptionsForOptions(options: LocalStorageOptions) -> [String: AnyObject]? {
public func storeOptionsForOptions(_ options: LocalStorageOptions) -> [String: AnyObject]? {
if options == .None {
if options == .none {
return self.storeOptions
}
var storeOptions = self.storeOptions ?? [:]
if options.contains(.AllowSynchronousLightweightMigration) {
if options.contains(.allowSynchronousLightweightMigration) {
storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
storeOptions[NSInferMappingModelAutomaticallyOption] = true
@@ -131,7 +131,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didAddToDataStack(dataStack: DataStack) {
public func didAddToDataStack(_ dataStack: DataStack) {
self.dataStack = dataStack
}
@@ -139,7 +139,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didRemoveFromDataStack(dataStack: DataStack) {
public func didRemoveFromDataStack(_ dataStack: DataStack) {
self.dataStack = nil
}
@@ -150,12 +150,12 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
The `NSURL` that points to the SQLite file
*/
public let fileURL: NSURL
public let fileURL: URL
/**
The `NSBundle`s from which to search mapping models for migrations
*/
public let mappingModelBundles: [NSBundle]
public let mappingModelBundles: [Bundle]
/**
Options that tell the `DataStack` how to setup the persistent store
@@ -165,7 +165,7 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
public func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws {
public func eraseStorageAndWait(soureModel: NSManagedObjectModel) throws {
// TODO: check if attached to persistent store
@@ -173,37 +173,37 @@ public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
try cs_autoreleasepool {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: fileURL,
let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType,
configurationName: self.configuration,
at: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
try journalUpdatingCoordinator.removePersistentStore(store)
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
try journalUpdatingCoordinator.remove(store)
try FileManager.default.removeItem(at: fileURL)
}
}
// MARK: Internal
internal static let defaultRootDirectory: NSURL = {
internal static let defaultRootDirectory: URL = {
#if os(tvOS)
let systemDirectorySearchPath = NSSearchPathDirectory.CachesDirectory
#else
let systemDirectorySearchPath = NSSearchPathDirectory.ApplicationSupportDirectory
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
return NSFileManager.defaultManager().URLsForDirectory(
return FileManager.default.urlsForDirectory(
systemDirectorySearchPath,
inDomains: .UserDomainMask
inDomains: .userDomainMask
).first!
}()
internal static let defaultFileURL = LegacySQLiteStore.defaultRootDirectory
.URLByAppendingPathComponent(DataStack.applicationName, isDirectory: false)
.URLByAppendingPathExtension("sqlite")
internal static let defaultFileURL = try! LegacySQLiteStore.defaultRootDirectory
.appendingPathComponent(DataStack.applicationName, isDirectory: false)
.appendingPathExtension("sqlite")
// MARK: Private
@@ -43,7 +43,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models (*.xcmappingmodel) for migration.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileURL: NSURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
public init(fileURL: URL, configuration: String? = nil, mappingModelBundles: [Bundle] = Bundle.allBundles, localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = fileURL
self.configuration = configuration
@@ -60,10 +60,10 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models (*.xcmappingmodel) for migration
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
public init(fileName: String, configuration: String? = nil, mappingModelBundles: [Bundle] = Bundle.allBundles, localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = SQLiteStore.defaultRootDirectory
.URLByAppendingPathComponent(fileName, isDirectory: false)
self.fileURL = try! SQLiteStore.defaultRootDirectory
.appendingPathComponent(fileName, isDirectory: false)
self.configuration = configuration
self.mappingModelBundles = mappingModelBundles
self.localStorageOptions = localStorageOptions
@@ -81,7 +81,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
self.fileURL = SQLiteStore.defaultFileURL
self.configuration = nil
self.mappingModelBundles = NSBundle.allBundles()
self.mappingModelBundles = Bundle.allBundles
self.localStorageOptions = nil
}
@@ -109,7 +109,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didAddToDataStack(dataStack: DataStack) {
public func didAddToDataStack(_ dataStack: DataStack) {
self.dataStack = dataStack
}
@@ -117,7 +117,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didRemoveFromDataStack(dataStack: DataStack) {
public func didRemoveFromDataStack(_ dataStack: DataStack) {
self.dataStack = nil
}
@@ -128,12 +128,12 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
The `NSURL` that points to the SQLite file
*/
public let fileURL: NSURL
public let fileURL: URL
/**
The `NSBundle`s from which to search mapping models for migrations
*/
public let mappingModelBundles: [NSBundle]
public let mappingModelBundles: [Bundle]
/**
Options that tell the `DataStack` how to setup the persistent store
@@ -143,15 +143,15 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
The options dictionary for the specified `LocalStorageOptions`
*/
public func storeOptionsForOptions(options: LocalStorageOptions) -> [String: AnyObject]? {
public func storeOptionsForOptions(_ options: LocalStorageOptions) -> [String: AnyObject]? {
if options == .None {
if options == .none {
return self.storeOptions
}
var storeOptions = self.storeOptions ?? [:]
if options.contains(.AllowSynchronousLightweightMigration) {
if options.contains(.allowSynchronousLightweightMigration) {
storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
storeOptions[NSInferMappingModelAutomaticallyOption] = true
@@ -162,7 +162,7 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
public func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws {
public func eraseStorageAndWait(soureModel: NSManagedObjectModel) throws {
// TODO: check if attached to persistent store
@@ -170,44 +170,43 @@ public final class SQLiteStore: LocalStorage, DefaultInitializableStore {
try cs_autoreleasepool {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: fileURL,
let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: self.dynamicType.storeType,
configurationName: self.configuration,
at: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
try journalUpdatingCoordinator.removePersistentStore(store)
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
try journalUpdatingCoordinator.remove(store)
try FileManager.default.removeItem(at: fileURL)
}
}
// MARK: Internal
internal static let defaultRootDirectory: NSURL = {
internal static let defaultRootDirectory: URL = {
#if os(tvOS)
let systemDirectorySearchPath = NSSearchPathDirectory.CachesDirectory
#else
let systemDirectorySearchPath = NSSearchPathDirectory.ApplicationSupportDirectory
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
let defaultSystemDirectory = NSFileManager
.defaultManager()
.URLsForDirectory(systemDirectorySearchPath, inDomains: .UserDomainMask).first!
let defaultSystemDirectory = FileManager.default
.urlsForDirectory(systemDirectorySearchPath, inDomains: .userDomainMask).first!
return defaultSystemDirectory.URLByAppendingPathComponent(
NSBundle.mainBundle().bundleIdentifier ?? "com.CoreStore.DataStack",
return try! defaultSystemDirectory.appendingPathComponent(
Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack",
isDirectory: true
)
}()
internal static let defaultFileURL = SQLiteStore.defaultRootDirectory
.URLByAppendingPathComponent(
(NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData",
internal static let defaultFileURL = try! SQLiteStore.defaultRootDirectory
.appendingPathComponent(
(Bundle.main.objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData",
isDirectory: false
)
.URLByAppendingPathExtension("sqlite")
.appendingPathExtension("sqlite")
// MARK: Private
@@ -54,12 +54,12 @@ public protocol StorageInterface: class {
/**
Do not call directly. Used by the `DataStack` internally.
*/
func didAddToDataStack(dataStack: DataStack)
func didAddToDataStack(_ dataStack: DataStack)
/**
Do not call directly. Used by the `DataStack` internally.
*/
func didRemoveFromDataStack(dataStack: DataStack)
func didRemoveFromDataStack(_ dataStack: DataStack)
}
@@ -82,27 +82,27 @@ public protocol DefaultInitializableStore: StorageInterface {
/**
The `LocalStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers.
*/
public struct LocalStorageOptions: OptionSetType, NilLiteralConvertible {
public struct LocalStorageOptions: OptionSet, NilLiteralConvertible {
/**
Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch
*/
public static let None = LocalStorageOptions(rawValue: 0)
public static let none = LocalStorageOptions(rawValue: 0)
/**
Tells the `DataStack` to delete and recreate the store on model mismatch, otherwise exceptions will be thrown on failure instead
*/
public static let RecreateStoreOnModelMismatch = LocalStorageOptions(rawValue: 1 << 0)
public static let recreateStoreOnModelMismatch = LocalStorageOptions(rawValue: 1 << 0)
/**
Tells the `DataStack` to prevent progressive migrations for the store
*/
public static let PreventProgressiveMigration = LocalStorageOptions(rawValue: 1 << 1)
public static let preventProgressiveMigration = LocalStorageOptions(rawValue: 1 << 1)
/**
Tells the `DataStack` to allow lightweight migration for the store when added synchronously
*/
public static let AllowSynchronousLightweightMigration = LocalStorageOptions(rawValue: 1 << 2)
public static let allowSynchronousLightweightMigration = LocalStorageOptions(rawValue: 1 << 2)
@@ -138,12 +138,12 @@ public protocol LocalStorage: StorageInterface {
/**
The `NSURL` that points to the store file
*/
var fileURL: NSURL { get }
var fileURL: URL { get }
/**
The `NSBundle`s from which to search mapping models (*.xcmappingmodel) for migrations
*/
var mappingModelBundles: [NSBundle] { get }
var mappingModelBundles: [Bundle] { get }
/**
Options that tell the `DataStack` how to setup the persistent store
@@ -153,21 +153,21 @@ public protocol LocalStorage: StorageInterface {
/**
The options dictionary for the specified `LocalStorageOptions`
*/
func storeOptionsForOptions(options: LocalStorageOptions) -> [String: AnyObject]?
func storeOptionsForOptions(_ options: LocalStorageOptions) -> [String: AnyObject]?
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. **Do not call directly!** The `sourceModel` argument is a hint for the existing store's model version. Implementers can use the `sourceModel` to perform necessary store operations. (SQLite stores for example, can convert WAL journaling mode to DELETE before deleting)
*/
func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws
func eraseStorageAndWait(soureModel: NSManagedObjectModel) throws
}
internal extension LocalStorage {
internal func matchesPersistentStore(persistentStore: NSPersistentStore) -> Bool {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
return persistentStore.type == self.dynamicType.storeType
&& persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName)
&& persistentStore.URL == self.fileURL
&& persistentStore.url == self.fileURL
}
}
@@ -177,22 +177,22 @@ internal extension LocalStorage {
/**
The `CloudStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers.
*/
public struct CloudStorageOptions: OptionSetType, NilLiteralConvertible {
public struct CloudStorageOptions: OptionSet, NilLiteralConvertible {
/**
Tells the `DataStack` that the store should not be migrated or recreated, and should simply fail on model mismatch
*/
public static let None = CloudStorageOptions(rawValue: 0)
public static let none = CloudStorageOptions(rawValue: 0)
/**
Tells the `DataStack` to delete and recreate the local store from the cloud store on model mismatch, otherwise exceptions will be thrown on failure instead
*/
public static let RecreateLocalStoreOnModelMismatch = CloudStorageOptions(rawValue: 1 << 0)
public static let recreateLocalStoreOnModelMismatch = CloudStorageOptions(rawValue: 1 << 0)
/**
Tells the `DataStack` to allow lightweight migration for the store when added synchronously
*/
public static let AllowSynchronousLightweightMigration = CloudStorageOptions(rawValue: 1 << 2)
public static let allowSynchronousLightweightMigration = CloudStorageOptions(rawValue: 1 << 2)
// MARK: OptionSetType
@@ -227,7 +227,7 @@ public protocol CloudStorage: StorageInterface {
/**
The `NSURL` that points to the store file
*/
var cacheFileURL: NSURL { get }
var cacheFileURL: URL { get }
/**
Options that tell the `DataStack` how to setup the persistent store
@@ -237,24 +237,24 @@ public protocol CloudStorage: StorageInterface {
/**
The options dictionary for the specified `CloudStorageOptions`
*/
func storeOptionsForOptions(options: CloudStorageOptions) -> [String: AnyObject]?
func storeOptionsForOptions(_ options: CloudStorageOptions) -> [String: AnyObject]?
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. **Do not call directly!** The `sourceModel` argument is a hint for the existing store's model version. Implementers can use the `sourceModel` to perform necessary store operations. (Cloud stores for example, can set the NSPersistentStoreRemoveUbiquitousMetadataOption option before deleting)
*/
func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws
func eraseStorageAndWait(soureModel: NSManagedObjectModel) throws
}
internal extension CloudStorage {
internal func matchesPersistentStore(persistentStore: NSPersistentStore) -> Bool {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
guard persistentStore.type == self.dynamicType.storeType
&& persistentStore.configurationName == (self.configuration ?? Into.defaultConfigurationName) else {
return false
}
guard persistentStore.URL == self.cacheFileURL else {
guard persistentStore.url == self.cacheFileURL else {
return false
}
@@ -42,7 +42,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.
*/
public func commit(completion: (result: SaveResult) -> Void = { _ in }) {
public func commit(_ completion: (result: SaveResult) -> Void = { _ in }) {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -71,7 +71,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- 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`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
public func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -97,7 +97,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
public override func create<T: NSManagedObject>(into: Into<T>) -> T {
public override func create<T: NSManagedObject>(_ into: Into<T>) -> T {
CoreStore.assert(
!self.isCommitted,
@@ -114,7 +114,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(object: T?) -> T? {
public override func edit<T: NSManagedObject>(_ object: T?) -> T? {
CoreStore.assert(
!self.isCommitted,
@@ -132,7 +132,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
public override func edit<T: NSManagedObject>(_ into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
CoreStore.assert(
!self.isCommitted,
@@ -147,7 +147,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter object: the `NSManagedObject` type to be deleted
*/
public override func delete(object: NSManagedObject?) {
public override func delete(_ object: NSManagedObject?) {
CoreStore.assert(
!self.isCommitted,
@@ -164,7 +164,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter object2: another `NSManagedObject` type to be deleted
- parameter objects: other `NSManagedObject`s type to be deleted
*/
public override func delete(object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
public override func delete(_ object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
CoreStore.assert(
!self.isCommitted,
@@ -179,7 +179,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
- parameter objects: the `NSManagedObject`s type to be deleted
*/
public override func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
public override func delete<S: Sequence where S.Iterator.Element: NSManagedObject>(_ objects: S) {
CoreStore.assert(
!self.isCommitted,
@@ -207,7 +207,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
if !self.isCommitted && self.hasChanges {
CoreStore.log(
.Warning,
.warning,
message: "The closure for the \(cs_typeName(self)) completed without being committed. All changes made within the transaction were discarded."
)
}
@@ -223,7 +223,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
if !self.isCommitted && self.hasChanges {
CoreStore.log(
.Warning,
.warning,
message: "The closure for the \(cs_typeName(self)) completed without being committed. All changes made within the transaction were discarded."
)
}
@@ -235,22 +235,4 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
// MARK: Private
private let closure: (transaction: AsynchronousDataTransaction) -> Void
// MARK: Deprecated
@available(*, deprecated=1.3.4, obsoleted=2.0.0, message="Resetting the context is inherently unsafe. This method will be removed in the near future. Use `beginUnsafe()` to create transactions with `undo` support.")
public func rollback() {
CoreStore.assert(
!self.isCommitted,
"Attempted to rollback an already committed \(cs_typeName(self))."
)
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to rollback a \(cs_typeName(self)) outside its designated queue."
)
self.context.reset()
}
}
+23 -23
View File
@@ -53,7 +53,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
public func create<T: NSManagedObject>(into: Into<T>) -> T {
public func create<T: NSManagedObject>(_ into: Into<T>) -> T {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -72,7 +72,7 @@ public /*abstract*/ class BaseDataTransaction {
case (let persistentStore?, _):
let object = entityClass.createInContext(context) as! T
context.assignObject(object, toPersistentStore: persistentStore)
context.assign(object, to: persistentStore)
return object
case (nil, true):
@@ -93,7 +93,7 @@ public /*abstract*/ class BaseDataTransaction {
case (let persistentStore?, _):
let object = entityClass.createInContext(context) as! T
context.assignObject(object, toPersistentStore: persistentStore)
context.assign(object, to: persistentStore)
return object
case (nil, true):
@@ -119,7 +119,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public func edit<T: NSManagedObject>(object: T?) -> T? {
public func edit<T: NSManagedObject>(_ object: T?) -> T? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -140,7 +140,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public func edit<T: NSManagedObject>(into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
public func edit<T: NSManagedObject>(_ into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -159,7 +159,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter object: the `NSManagedObject` to be deleted
*/
public func delete(object: NSManagedObject?) {
public func delete(_ object: NSManagedObject?) {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -179,7 +179,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter object2: another `NSManagedObject` to be deleted
- parameter objects: other `NSManagedObject`s to be deleted
*/
public func delete(object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
public func delete(_ object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
self.delete(([object1, object2] + objects).flatMap { $0 })
}
@@ -189,7 +189,7 @@ public /*abstract*/ class BaseDataTransaction {
- parameter objects: the `NSManagedObject`s to be deleted
*/
public func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
public func delete<S: Sequence where S.Iterator.Element: NSManagedObject>(_ objects: S) {
CoreStore.assert(
self.isRunningInAllowedQueue(),
@@ -243,7 +243,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were inserted to the transaction.
*/
@warn_unused_result
public func insertedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
public func insertedObjects<T: NSManagedObject>(_ entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -284,7 +284,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction.
*/
@warn_unused_result
public func insertedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
public func insertedObjectIDs<T: NSManagedObject>(_ entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -295,7 +295,7 @@ public /*abstract*/ class BaseDataTransaction {
"Attempted to access inserted objects IDs from an already committed \(cs_typeName(self))."
)
return Set(self.context.insertedObjects.filter { $0.isKindOfClass(entity) }.map { $0.objectID })
return Set(self.context.insertedObjects.filter { $0.isKind(of: entity) }.map { $0.objectID })
}
/**
@@ -325,7 +325,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were updated in the transaction.
*/
@warn_unused_result
public func updatedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
public func updatedObjects<T: NSManagedObject>(_ entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -336,7 +336,7 @@ public /*abstract*/ class BaseDataTransaction {
"Attempted to access updated objects from an already committed \(cs_typeName(self))."
)
return Set(self.context.updatedObjects.filter { $0.isKindOfClass(entity) }.map { $0 as! T })
return Set(self.context.updatedObjects.filter { $0.isKind(of: entity) }.map { $0 as! T })
}
/**
@@ -366,7 +366,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction.
*/
@warn_unused_result
public func updatedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
public func updatedObjectIDs<T: NSManagedObject>(_ entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -377,7 +377,7 @@ public /*abstract*/ class BaseDataTransaction {
"Attempted to access updated object IDs from an already committed \(cs_typeName(self))."
)
return Set(self.context.updatedObjects.filter { $0.isKindOfClass(entity) }.map { $0.objectID })
return Set(self.context.updatedObjects.filter { $0.isKind(of: entity) }.map { $0.objectID })
}
/**
@@ -407,7 +407,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were deleted from the transaction.
*/
@warn_unused_result
public func deletedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
public func deletedObjects<T: NSManagedObject>(_ entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -418,7 +418,7 @@ public /*abstract*/ class BaseDataTransaction {
"Attempted to access deleted objects from an already committed \(cs_typeName(self))."
)
return Set(self.context.deletedObjects.filter { $0.isKindOfClass(entity) }.map { $0 as! T })
return Set(self.context.deletedObjects.filter { $0.isKind(of: entity) }.map { $0 as! T })
}
/**
@@ -449,7 +449,7 @@ public /*abstract*/ class BaseDataTransaction {
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
@warn_unused_result
public func deletedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
public func deletedObjectIDs<T: NSManagedObject>(_ entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
@@ -460,7 +460,7 @@ public /*abstract*/ class BaseDataTransaction {
"Attempted to access deleted object IDs from an already committed \(cs_typeName(self))."
)
return Set(self.context.deletedObjects.filter { $0.isKindOfClass(entity) }.map { $0.objectID })
return Set(self.context.deletedObjects.filter { $0.isKind(of: entity) }.map { $0.objectID })
}
@@ -479,9 +479,9 @@ public /*abstract*/ class BaseDataTransaction {
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool, bypassesQueueing: Bool) {
let context = mainContext.temporaryContextInTransactionWithConcurrencyType(
queue == .Main
? .MainQueueConcurrencyType
: .PrivateQueueConcurrencyType
queue == .main
? .mainQueueConcurrencyType
: .privateQueueConcurrencyType
)
self.transactionQueue = queue
self.context = context
@@ -495,7 +495,7 @@ public /*abstract*/ class BaseDataTransaction {
}
else if context.undoManager == nil {
context.undoManager = NSUndoManager()
context.undoManager = UndoManager()
}
}
@@ -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`.
*/
public static func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) {
public static func beginAsynchronous(_ closure: (transaction: AsynchronousDataTransaction) -> Void) {
self.defaultStack.beginAsynchronous(closure)
}
@@ -46,7 +46,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`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
public static func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
public static func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
return self.defaultStack.beginSynchronous(closure)
}
@@ -58,7 +58,7 @@ public extension CoreStore {
- returns: a `UnsafeDataTransaction` instance where creates, updates, and deletes can be made.
*/
@warn_unused_result
public static func beginUnsafe(supportsUndo supportsUndo: Bool = false) -> UnsafeDataTransaction {
public static func beginUnsafe(supportsUndo: Bool = false) -> UnsafeDataTransaction {
return self.defaultStack.beginUnsafe(supportsUndo: supportsUndo)
}
@@ -70,14 +70,4 @@ public extension CoreStore {
self.defaultStack.refreshAndMergeAllObjects()
}
// MARK: Deprecated
@available(*, deprecated=1.3.1, obsoleted=2.0.0, renamed="beginUnsafe")
@warn_unused_result
public static func beginDetached() -> UnsafeDataTransaction {
return self.beginUnsafe()
}
}
@@ -39,7 +39,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`.
*/
public func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) {
public func beginAsynchronous(_ closure: (transaction: AsynchronousDataTransaction) -> Void) {
AsynchronousDataTransaction(
mainContext: self.rootSavingContext,
@@ -53,7 +53,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`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
public func beginSynchronous(_ closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
return SynchronousDataTransaction(
mainContext: self.rootSavingContext,
@@ -68,13 +68,13 @@ public extension DataStack {
- returns: a `UnsafeDataTransaction` instance where creates, updates, and deletes can be made.
*/
@warn_unused_result
public func beginUnsafe(supportsUndo supportsUndo: Bool = false) -> UnsafeDataTransaction {
public func beginUnsafe(supportsUndo: Bool = false) -> UnsafeDataTransaction {
return UnsafeDataTransaction(
mainContext: self.rootSavingContext,
queue: .createSerial(
"com.coreStore.dataStack.unsafeTransactionQueue",
targetQueue: .UserInitiated
targetQueue: .userInitiated
),
supportsUndo: supportsUndo
)
@@ -86,20 +86,10 @@ public extension DataStack {
public func refreshAndMergeAllObjects() {
CoreStore.assert(
NSThread.isMainThread(),
Thread.isMainThread,
"Attempted to refresh entities outside their designated queue."
)
self.mainContext.refreshAndMergeAllObjects()
}
// MARK: Deprecated
@available(*, deprecated=1.3.1, obsoleted=2.0.0, renamed="beginUnsafe")
@warn_unused_result
public func beginDetached() -> UnsafeDataTransaction {
return self.beginUnsafe()
}
}
@@ -48,17 +48,17 @@ public extension NSManagedObject {
// MARK: Internal
@nonobjc
internal class func createInContext(context: NSManagedObjectContext) -> Self {
internal class func createInContext(_ context: NSManagedObjectContext) -> Self {
return self.init(
return self.`init`(entity:insertInto:)(
entity: context.entityDescriptionForEntityType(self)!,
insertIntoManagedObjectContext: context
insertInto: context
)
}
@nonobjc
internal func deleteFromContext() {
self.managedObjectContext?.deleteObject(self)
self.managedObjectContext?.delete(self)
}
}

Some files were not shown because too many files have changed in this diff Show More