comments cleanup

This commit is contained in:
John Rommel Estropia
2016-02-17 01:38:26 +09:00
parent def105e73a
commit 66892f22a3
47 changed files with 1749 additions and 1750 deletions

View File

@@ -31,9 +31,9 @@ import CoreData
public extension NSFetchedResultsController { public extension NSFetchedResultsController {
/**
// MARK: Public Utility for creating an `NSFetchedResultsController` from a `DataStack`. This is useful to partially support Objective-C classes by passing an `NSFetchedResultsController` instance instead of a `ListMonitor`.
*/
public func createForStack<T: NSManagedObject>(dataStack: DataStack, fetchRequest: NSFetchRequest, from: From<T>? = nil, sectionBy: SectionBy? = nil, fetchClauses: [FetchClause]) -> NSFetchedResultsController { public func createForStack<T: NSManagedObject>(dataStack: DataStack, fetchRequest: NSFetchRequest, from: From<T>? = nil, sectionBy: SectionBy? = nil, fetchClauses: [FetchClause]) -> NSFetchedResultsController {
return CoreStoreFetchedResultsController<T>( return CoreStoreFetchedResultsController<T>(

View File

@@ -32,11 +32,11 @@ import CoreData
public extension NSManagedObject { public extension NSManagedObject {
/** /**
Provides a convenience wrapper for accessing `primitiveValueForKey(...)` with proper calls to `willAccessValueForKey(...)` and `didAccessValueForKey(...)`. This is useful when implementing accessor methods for transient attributes. Provides a convenience wrapper for accessing `primitiveValueForKey(...)` with proper calls to `willAccessValueForKey(...)` and `didAccessValueForKey(...)`. This is useful when implementing accessor methods for transient attributes.
- parameter KVCKey: the KVC key - parameter KVCKey: the KVC key
- returns: the primitive value for the KVC key - returns: the primitive value for the KVC key
*/ */
@warn_unused_result @warn_unused_result
public func accessValueForKVCKey(KVCKey: KeyPath) -> AnyObject? { public func accessValueForKVCKey(KVCKey: KeyPath) -> AnyObject? {
@@ -48,11 +48,11 @@ public extension NSManagedObject {
} }
/** /**
Provides a convenience wrapper for setting `setPrimitiveValue(...)` with proper calls to `willChangeValueForKey(...)` and `didChangeValueForKey(...)`. This is useful when implementing mutator methods for transient attributes. Provides a convenience wrapper for setting `setPrimitiveValue(...)` with proper calls to `willChangeValueForKey(...)` and `didChangeValueForKey(...)`. This is useful when implementing mutator methods for transient attributes.
- parameter value: the value to set the KVC key with - parameter value: the value to set the KVC key with
- parameter KVCKey: the KVC key - parameter KVCKey: the KVC key
*/ */
public func setValue(value: AnyObject?, forKVCKey KVCKey: KeyPath) { public func setValue(value: AnyObject?, forKVCKey KVCKey: KeyPath) {
self.willChangeValueForKey(KVCKey) self.willChangeValueForKey(KVCKey)
@@ -61,16 +61,16 @@ public extension NSManagedObject {
} }
/** /**
Re-faults the object to use the latest values from the persistent store Re-faults the object to use the latest values from the persistent store
*/ */
public func refreshAsFault() { public func refreshAsFault() {
self.managedObjectContext?.refreshObject(self, mergeChanges: false) self.managedObjectContext?.refreshObject(self, mergeChanges: false)
} }
/** /**
Re-faults the object to use the latest values from the persistent store and merges previously pending changes back Re-faults the object to use the latest values from the persistent store and merges previously pending changes back
*/ */
public func refreshAndMerge() { public func refreshAndMerge() {
self.managedObjectContext?.refreshObject(self, mergeChanges: true) self.managedObjectContext?.refreshObject(self, mergeChanges: true)

View File

@@ -33,12 +33,10 @@ import Foundation
public extension NSProgress { public extension NSProgress {
// MARK: Public
/** /**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO. Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
- parameter closure: the closure to execute on progress change - parameter closure: the closure to execute on progress change
*/ */
public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) { public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
self.progressObserver.progressHandler = closure self.progressObserver.progressHandler = closure

View File

@@ -28,4 +28,3 @@
FOUNDATION_EXPORT double CoreStoreVersionNumber; FOUNDATION_EXPORT double CoreStoreVersionNumber;
FOUNDATION_EXPORT const unsigned char CoreStoreVersionString[]; FOUNDATION_EXPORT const unsigned char CoreStoreVersionString[];

View File

@@ -32,17 +32,15 @@ import CoreData
// MARK: - CoreStore // MARK: - CoreStore
/** /**
`CoreStore` is the main entry point for all other APIs. `CoreStore` is the main entry point for all other APIs.
*/ */
public enum CoreStore { public enum CoreStore {
// MARK: Public
/** /**
The default `DataStack` instance to be used. If `defaultStack` is not set before the first time accessed, a default-configured `DataStack` will be created. The default `DataStack` instance to be used. If `defaultStack` is not set before the first time accessed, a default-configured `DataStack` will be created.
Changing the `defaultStack` is thread safe, but it is recommended to setup `DataStacks` on a common queue (e.g. the main queue). Changing the `defaultStack` is thread safe, but it is recommended to setup `DataStacks` on a common queue (e.g. the main queue).
*/ */
public static var defaultStack: DataStack { public static var defaultStack: DataStack {
get { get {

View File

@@ -31,14 +31,12 @@ import CoreData
public extension BaseDataTransaction { public extension BaseDataTransaction {
// MARK: Public
/** /**
Fetches the `NSManagedObject` instance in the transaction's context from a reference created from a transaction or from a different managed object context. Fetches the `NSManagedObject` instance in the transaction's context from a reference created from a transaction or from a different managed object context.
- parameter object: a reference to the object created/fetched outside the transaction - parameter object: a reference to the object created/fetched outside the transaction
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject>(object: T) -> T? { public func fetchExisting<T: NSManagedObject>(object: T) -> T? {
@@ -53,11 +51,11 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObject` instance in the transaction's context from an `NSManagedObjectID`. Fetches the `NSManagedObject` instance in the transaction's context from an `NSManagedObjectID`.
- parameter objectID: the `NSManagedObjectID` for the object - parameter objectID: the `NSManagedObjectID` for the object
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? { public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
@@ -72,11 +70,11 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObject` instances in the transaction's context from references created from a transaction or from a different managed object context. Fetches the `NSManagedObject` instances in the transaction's context from references created from a transaction or from a different managed object context.
- parameter objects: an array of `NSManagedObject`s created/fetched outside the transaction - parameter objects: an array of `NSManagedObject`s created/fetched outside the transaction
- returns: the `NSManagedObject` array for objects that exists in the transaction - returns: the `NSManagedObject` array for objects that exists in the transaction
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
@@ -84,11 +82,11 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObject` instances in the transaction's context from a list of `NSManagedObjectID`. Fetches the `NSManagedObject` instances in the transaction's context from a list of `NSManagedObjectID`.
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the transaction - returns: the `NSManagedObject` array for objects that exists in the transaction
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
@@ -96,12 +94,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -114,12 +112,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -132,12 +130,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -150,12 +148,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -168,12 +166,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -186,12 +184,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -204,12 +202,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -222,12 +220,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -240,12 +238,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -258,12 +256,12 @@ public extension BaseDataTransaction {
} }
/** /**
Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -276,12 +274,12 @@ public extension BaseDataTransaction {
} }
/** /**
Deletes all `NSManagedObject`s that satisfy the specified `DeleteClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Deletes all `NSManagedObject`s that satisfy the specified `DeleteClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `NSManagedObject`s deleted - 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( CoreStore.assert(
@@ -293,12 +291,12 @@ public extension BaseDataTransaction {
} }
/** /**
Deletes all `NSManagedObject`s that satisfy the specified `DeleteClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Deletes all `NSManagedObject`s that satisfy the specified `DeleteClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter deleteClauses: a series of `DeleteClause` instances for the delete request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `NSManagedObject`s deleted - 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( CoreStore.assert(
@@ -310,15 +308,15 @@ public extension BaseDataTransaction {
} }
/** /**
Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -331,15 +329,15 @@ public extension BaseDataTransaction {
} }
/** /**
Queries aggregate values or aggregates as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries aggregate values or aggregates as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -352,15 +350,15 @@ public extension BaseDataTransaction {
} }
/** /**
Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {
@@ -373,15 +371,15 @@ public extension BaseDataTransaction {
} }
/** /**
Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {

View File

@@ -30,38 +30,77 @@ import CoreData
// MARK: - From // MARK: - From
/** /**
A `Form` clause binds the `NSManagedObject` entity type to the generics type system. A `From` clause specifies the source entity and source persistent store for fetch and query methods. A common usage is to just indicate the entity:
*/ ```
let person = transaction.fetchOne(From(MyPersonEntity))
```
For cases where multiple `NSPersistentStore`s contain the same entity, the source configuration's name needs to be specified as well:
```
let person = transaction.fetchOne(From<MyPersonEntity>("Configuration1"))
```
*/
public struct From<T: NSManagedObject> { public struct From<T: NSManagedObject> {
// MARK: Public
/** /**
Initializes a `From` clause with the specified entity type and configuration. Initializes a `From` clause.
Sample Usage: Sample Usage:
```
let person = transaction.fetchOne(From<MyPersonEntity>()) let people = transaction.fetchAll(From<MyPersonEntity>())
*/ ```
*/
public init(){ public init(){
self.init(entityClass: T.self) self.init(entityClass: T.self)
} }
/**
Initializes a `From` clause with the specified entity type.
Sample Usage:
```
let people = transaction.fetchAll(From<MyPersonEntity>())
```
- parameter entity: the `NSManagedObject` type to be created
*/
public init(_ entity: T.Type) { public init(_ entity: T.Type) {
self.init(entityClass: entity) self.init(entityClass: entity)
} }
/**
Initializes a `From` clause with the specified entity class.
Sample Usage:
```
let people = transaction.fetchAll(From<MyPersonEntity>())
```
- parameter entityClass: the `NSManagedObject` class type to be created
*/
public init(_ entityClass: AnyClass) { public init(_ entityClass: AnyClass) {
self.init(entityClass: entityClass) self.init(entityClass: entityClass)
} }
/**
Initializes a `From` clause with the specified configurations.
Sample Usage:
```
let people = transaction.fetchAll(From<MyPersonEntity>(nil, "Configuration1"))
```
- parameter configuration: the `NSPersistentStore` configuration name to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration.
- parameter otherConfigurations: an optional list of other configuration names to associate objects from (see `configuration` parameter)
*/
public init(_ configuration: String?, otherConfigurations: String?...) { public init(_ configuration: String?, otherConfigurations: String?...) {
self.init(entityClass: T.self, configurations: [configuration] + otherConfigurations) self.init(entityClass: T.self, configurations: [configuration] + otherConfigurations)
} }
/**
Initializes a `From` clause with the specified configurations.
Sample Usage:
```
let people = transaction.fetchAll(From<MyPersonEntity>(["Configuration1", "Configuration2"]))
```
- parameter configurations: a list of `NSPersistentStore` configuration names to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration.
*/
public init(_ configurations: [String?]) { public init(_ configurations: [String?]) {
self.init(entityClass: T.self, configurations: configurations) self.init(entityClass: T.self, configurations: configurations)

View File

@@ -30,36 +30,34 @@ import CoreData
// MARK: - GroupBy // MARK: - GroupBy
/** /**
The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path. The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path.
*/ */
public struct GroupBy: QueryClause { public struct GroupBy: QueryClause {
// MARK: Public
/** /**
Initializes a `GroupBy` clause with a list of key path strings Initializes a `GroupBy` clause with a list of key path strings
- parameter keyPaths: a list of key path strings to group results with - parameter keyPaths: a list of key path strings to group results with
*/ */
public init(_ keyPaths: [KeyPath]) { public init(_ keyPaths: [KeyPath]) {
self.keyPaths = keyPaths self.keyPaths = keyPaths
} }
/** /**
Initializes a `GroupBy` clause with an empty list of key path strings Initializes a `GroupBy` clause with an empty list of key path strings
*/ */
public init() { public init() {
self.init([]) self.init([])
} }
/** /**
Initializes a `GroupBy` clause with a list of key path strings Initializes a `GroupBy` clause with a list of key path strings
- parameter keyPath: a key path string to group results with - parameter keyPath: a key path string to group results with
- parameter keyPaths: a series of key path strings to group results with - parameter keyPaths: a series of key path strings to group results with
*/ */
public init(_ keyPath: KeyPath, _ keyPaths: KeyPath...) { public init(_ keyPath: KeyPath, _ keyPaths: KeyPath...) {
self.init([keyPath] + keyPaths) self.init([keyPath] + keyPaths)
@@ -72,7 +70,7 @@ public struct GroupBy: QueryClause {
public func applyToFetchRequest(fetchRequest: NSFetchRequest) { public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.propertiesToGroupBy != nil { if let keyPaths = fetchRequest.propertiesToGroupBy as? [String] where keyPaths != self.keyPaths {
CoreStore.log( CoreStore.log(
.Warning, .Warning,

View File

@@ -46,18 +46,18 @@ public typealias KeyPath = String
// MARK: - SortKey // MARK: - SortKey
/** /**
The `SortKey` is passed to the `OrderBy` clause to indicate the sort keys and their sort direction. The `SortKey` is passed to the `OrderBy` clause to indicate the sort keys and their sort direction.
*/ */
public enum SortKey { public enum SortKey {
/** /**
Indicates that the `KeyPath` should be sorted in ascending order 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 Indicates that the `KeyPath` should be sorted in descending order
*/ */
case Descending(KeyPath) case Descending(KeyPath)
} }
@@ -65,45 +65,43 @@ public enum SortKey {
// MARK: - OrderBy // MARK: - OrderBy
/** /**
The `OrderBy` clause specifies the sort order for results for a fetch or a query. The `OrderBy` clause specifies the sort order for results for a fetch or a query.
*/ */
public struct OrderBy: FetchClause, QueryClause, DeleteClause { public struct OrderBy: FetchClause, QueryClause, DeleteClause {
// MARK: Public
/** /**
Initializes a `OrderBy` clause with a list of sort descriptors Initializes a `OrderBy` clause with a list of sort descriptors
- parameter sortDescriptors: a series of `NSSortDescriptor`s - parameter sortDescriptors: a series of `NSSortDescriptor`s
*/ */
public init(_ sortDescriptors: [NSSortDescriptor]) { public init(_ sortDescriptors: [NSSortDescriptor]) {
self.sortDescriptors = sortDescriptors self.sortDescriptors = sortDescriptors
} }
/** /**
Initializes a `OrderBy` clause with an empty list of sort descriptors Initializes a `OrderBy` clause with an empty list of sort descriptors
*/ */
public init() { public init() {
self.init([NSSortDescriptor]()) self.init([NSSortDescriptor]())
} }
/** /**
Initializes a `OrderBy` clause with a single sort descriptor Initializes a `OrderBy` clause with a single sort descriptor
- parameter sortDescriptor: a `NSSortDescriptor` - parameter sortDescriptor: a `NSSortDescriptor`
*/ */
public init(_ sortDescriptor: NSSortDescriptor) { public init(_ sortDescriptor: NSSortDescriptor) {
self.init([sortDescriptor]) self.init([sortDescriptor])
} }
/** /**
Initializes a `OrderBy` clause with a series of `SortKey`s Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a series of `SortKey`s - parameter sortKey: a series of `SortKey`s
*/ */
public init(_ sortKey: [SortKey]) { public init(_ sortKey: [SortKey]) {
self.init( self.init(
@@ -122,11 +120,11 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause {
} }
/** /**
Initializes a `OrderBy` clause with a series of `SortKey`s Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a single `SortKey` - parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of `SortKey`s - parameter sortKeys: a series of `SortKey`s
*/ */
public init(_ sortKey: SortKey, _ sortKeys: SortKey...) { public init(_ sortKey: SortKey, _ sortKeys: SortKey...) {
self.init([sortKey] + sortKeys) self.init([sortKey] + sortKeys)
@@ -139,7 +137,7 @@ public struct OrderBy: FetchClause, QueryClause, DeleteClause {
public func applyToFetchRequest(fetchRequest: NSFetchRequest) { public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.sortDescriptors != nil { if let sortDescriptors = fetchRequest.sortDescriptors where sortDescriptors != self.sortDescriptors {
CoreStore.log( CoreStore.log(
.Warning, .Warning,

View File

@@ -30,16 +30,16 @@ import CoreData
// MARK: - SelectResultType // MARK: - SelectResultType
/** /**
The `SelectResultType` protocol is implemented by return types supported by the `Select` clause. The `SelectResultType` protocol is implemented by return types supported by the `Select` clause.
*/ */
public protocol SelectResultType { } public protocol SelectResultType { }
// MARK: - SelectValueResultType // MARK: - SelectValueResultType
/** /**
The `SelectValueResultType` protocol is implemented by return types supported by the `queryValue(...)` methods. The `SelectValueResultType` protocol is implemented by return types supported by the `queryValue(...)` methods.
*/ */
public protocol SelectValueResultType: SelectResultType { public protocol SelectValueResultType: SelectResultType {
static func fromResultObject(result: AnyObject) -> Self? static func fromResultObject(result: AnyObject) -> Self?
@@ -49,8 +49,8 @@ public protocol SelectValueResultType: SelectResultType {
// MARK: - SelectAttributesResultType // MARK: - SelectAttributesResultType
/** /**
The `SelectValueResultType` protocol is implemented by return types supported by the `queryAttributes(...)` methods. The `SelectValueResultType` protocol is implemented by return types supported by the `queryAttributes(...)` methods.
*/ */
public protocol SelectAttributesResultType: SelectResultType { public protocol SelectAttributesResultType: SelectResultType {
static func fromResultObjects(result: [AnyObject]) -> [[NSString: AnyObject]] static func fromResultObjects(result: [AnyObject]) -> [[NSString: AnyObject]]
@@ -60,49 +60,47 @@ public protocol SelectAttributesResultType: SelectResultType {
// MARK: - SelectTerm // MARK: - SelectTerm
/** /**
The `SelectTerm` is passed to the `Select` clause to indicate the attributes/aggregate keys to be queried. The `SelectTerm` is passed to the `Select` clause to indicate the attributes/aggregate keys to be queried.
*/ */
public enum SelectTerm: StringLiteralConvertible { public enum SelectTerm: StringLiteralConvertible {
// MARK: Public
/** /**
Provides a `SelectTerm` to a `Select` clause for querying an entity attribute. A shorter way to do the same is to assign from the string keypath directly: Provides a `SelectTerm` to a `Select` clause for querying an entity attribute. A shorter way to do the same is to assign from the string keypath directly:
```
let fullName = CoreStore.queryValue( let fullName = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<String>(.Attribute("fullName")), Select<String>(.Attribute("fullName")),
Where("employeeID", isEqualTo: 1111) Where("employeeID", isEqualTo: 1111)
) )
```
is equivalent to: is equivalent to:
```
let fullName = CoreStore.queryValue( let fullName = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<String>("fullName"), Select<String>("fullName"),
Where("employeeID", isEqualTo: 1111) Where("employeeID", isEqualTo: 1111)
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- returns: a `SelectTerm` to a `Select` clause for querying an entity attribute - 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)
} }
/** /**
Provides a `SelectTerm` to a `Select` clause for querying the average value of an attribute. Provides a `SelectTerm` to a `Select` clause for querying the average value of an attribute.
```
let averageAge = CoreStore.queryValue( let averageAge = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Average("age")) Select<Int>(.Average("age"))
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- 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 - 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 - 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(
@@ -114,17 +112,17 @@ public enum SelectTerm: StringLiteralConvertible {
} }
/** /**
Provides a `SelectTerm` to a `Select` clause for a count query. Provides a `SelectTerm` to a `Select` clause for a count query.
```
let numberOfEmployees = CoreStore.queryValue( let numberOfEmployees = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Count("employeeID")) Select<Int>(.Count("employeeID"))
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- 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 - 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 - 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(
@@ -136,17 +134,17 @@ public enum SelectTerm: StringLiteralConvertible {
} }
/** /**
Provides a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute. Provides a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute.
```
let maximumAge = CoreStore.queryValue( let maximumAge = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Maximum("age")) Select<Int>(.Maximum("age"))
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- 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 - 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 - 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(
@@ -158,17 +156,17 @@ public enum SelectTerm: StringLiteralConvertible {
} }
/** /**
Provides a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute. Provides a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute.
```
let minimumAge = CoreStore.queryValue( let minimumAge = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Minimum("age")) Select<Int>(.Minimum("age"))
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- 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 - 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 - 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(
@@ -180,17 +178,17 @@ public enum SelectTerm: StringLiteralConvertible {
} }
/** /**
Provides a `SelectTerm` to a `Select` clause for querying the sum value for an attribute. Provides a `SelectTerm` to a `Select` clause for querying the sum value for an attribute.
```
let totalAge = CoreStore.queryValue( let totalAge = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Sum("age")) Select<Int>(.Sum("age"))
) )
```
- parameter keyPath: the attribute name - parameter keyPath: the attribute name
- 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 - 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 - 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(
@@ -230,68 +228,66 @@ public enum SelectTerm: StringLiteralConvertible {
// MARK: - Select // MARK: - Select
/** /**
The `Select` clause indicates the attribute / aggregate value to be queried. The generic type is a `SelectResultType`, and will be used as the return type for the query. The `Select` clause indicates the attribute / aggregate value to be queried. The generic type is a `SelectResultType`, and will be used as the return type for the query.
You can bind the return type by specializing the initializer: You can bind the return type by specializing the initializer:
```
let maximumAge = CoreStore.queryValue( let maximumAge = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select<Int>(.Maximum("age")) Select<Int>(.Maximum("age"))
) )
```
or by casting the type of the return value: or by casting the type of the return value:
```
let maximumAge: Int = CoreStore.queryValue( let maximumAge: Int = CoreStore.queryValue(
From(MyPersonEntity), From(MyPersonEntity),
Select(.Maximum("age")) Select(.Maximum("age"))
) )
```
Valid return types depend on the query: Valid return types depend on the query:
- for `queryValue(...)` methods: - for `queryValue(...)` methods:
- `Bool` - `Bool`
- `Int8` - `Int8`
- `Int16` - `Int16`
- `Int32` - `Int32`
- `Int64` - `Int64`
- `Double` - `Double`
- `Float` - `Float`
- `String` - `String`
- `NSNumber` - `NSNumber`
- `NSString` - `NSString`
- `NSDecimalNumber` - `NSDecimalNumber`
- `NSDate` - `NSDate`
- `NSData` - `NSData`
- `NSManagedObjectID` - `NSManagedObjectID`
- `NSString` - `NSString`
- for `queryAttributes(...)` methods: - for `queryAttributes(...)` methods:
- `NSDictionary` - `NSDictionary`
- parameter sortDescriptors: a series of `NSSortDescriptor`s - parameter sortDescriptors: a series of `NSSortDescriptor`s
*/ */
public struct Select<T: SelectResultType> { public struct Select<T: SelectResultType> {
// MARK: Public
/** /**
The `SelectResultType` type for the query's return value The `SelectResultType` type for the query's return value
*/ */
public typealias ReturnType = T public typealias ReturnType = T
/** /**
Initializes a `Select` clause with a list of `SelectTerm`s Initializes a `Select` clause with a list of `SelectTerm`s
- parameter selectTerm: a `SelectTerm` - parameter selectTerm: a `SelectTerm`
- parameter selectTerms: a series of `SelectTerm`s - parameter selectTerms: a series of `SelectTerm`s
*/ */
public init(_ selectTerm: SelectTerm, _ selectTerms: SelectTerm...) { public init(_ selectTerm: SelectTerm, _ selectTerms: SelectTerm...) {
self.selectTerms = [selectTerm] + selectTerms self.selectTerms = [selectTerm] + selectTerms
} }
// MARK: Internal // MARK: Internal
internal func applyToFetchRequest(fetchRequest: NSFetchRequest) { internal func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.propertiesToFetch != nil { if fetchRequest.propertiesToFetch != nil {

View File

@@ -30,27 +30,25 @@ import CoreData
// MARK: - Tweak // MARK: - Tweak
/** /**
The `Tweak` clause allows fine-tuning the `NSFetchRequest` for a fetch or query. The `Tweak` clause allows fine-tuning the `NSFetchRequest` for a fetch or query.
Sample usage:
Sample usage: ```
let employees = transaction.fetchAll(
let employees = transaction.fetchAll( From(MyPersonEntity),
From(MyPersonEntity), Tweak { (fetchRequest) -> Void in
Tweak { (fetchRequest) -> Void in fetchRequest.includesPendingChanges = false
fetchRequest.includesPendingChanges = false fetchRequest.fetchLimit = 5
fetchRequest.fetchLimit = 5 }
} )
) ```
*/ */
public struct Tweak: FetchClause, QueryClause, DeleteClause { public struct Tweak: FetchClause, QueryClause, DeleteClause {
// MARK: Public
/** /**
Initializes a `Tweak` clause with a closure where the `NSFetchRequest` may be configured. Initializes a `Tweak` clause with a closure where the `NSFetchRequest` may be configured.
- parameter customization: a list of key path strings to group results with - parameter customization: a list of key path strings to group results with
*/ */
public init(_ customization: (fetchRequest: NSFetchRequest) -> Void) { public init(_ customization: (fetchRequest: NSFetchRequest) -> Void) {
self.customization = customization self.customization = customization
@@ -65,5 +63,7 @@ public struct Tweak: FetchClause, QueryClause, DeleteClause {
} }
// MARK: Private
private let customization: (fetchRequest: NSFetchRequest) -> Void private let customization: (fetchRequest: NSFetchRequest) -> Void
} }

View File

@@ -46,68 +46,66 @@ public prefix func !(clause: Where) -> Where {
// MARK: - Where // MARK: - Where
/** /**
The `Where` clause specifies the conditions for a fetch or a query. The `Where` clause specifies the conditions for a fetch or a query.
*/ */
public struct Where: FetchClause, QueryClause, DeleteClause { public struct Where: FetchClause, QueryClause, DeleteClause {
// MARK: Public
/** /**
Initializes a `Where` clause with an `NSPredicate` Initializes a `Where` clause with an `NSPredicate`
- parameter predicate: the `NSPredicate` for the fetch or query - parameter predicate: the `NSPredicate` for the fetch or query
*/ */
public init(_ predicate: NSPredicate) { public init(_ predicate: NSPredicate) {
self.predicate = predicate self.predicate = predicate
} }
/** /**
Initializes a `Where` clause with a predicate that always evaluates to `true` Initializes a `Where` clause with a predicate that always evaluates to `true`
*/ */
public init() { public init() {
self.init(true) self.init(true)
} }
/** /**
Initializes a `Where` clause with a predicate that always evaluates to the specified boolean value Initializes a `Where` clause with a predicate that always evaluates to the specified boolean value
- parameter value: the boolean value for the predicate - parameter value: the boolean value for the predicate
*/ */
public init(_ value: Bool) { public init(_ value: Bool) {
self.init(NSPredicate(value: value)) self.init(NSPredicate(value: value))
} }
/** /**
Initializes a `Where` clause with a predicate using the specified string format and arguments Initializes a `Where` clause with a predicate using the specified string format and arguments
- parameter format: the format string for the predicate - parameter format: the format string for the predicate
- parameter args: the arguments for `format` - parameter args: the arguments for `format`
*/ */
public init(_ format: String, _ args: NSObject...) { public init(_ format: String, _ args: NSObject...) {
self.init(NSPredicate(format: format, argumentArray: args)) self.init(NSPredicate(format: format, argumentArray: args))
} }
/** /**
Initializes a `Where` clause with a predicate using the specified string format and arguments Initializes a `Where` clause with a predicate using the specified string format and arguments
- parameter format: the format string for the predicate - parameter format: the format string for the predicate
- parameter argumentArray: the arguments for `format` - parameter argumentArray: the arguments for `format`
*/ */
public init(_ format: String, argumentArray: [NSObject]?) { public init(_ format: String, argumentArray: [NSObject]?) {
self.init(NSPredicate(format: format, argumentArray: argumentArray)) self.init(NSPredicate(format: format, argumentArray: argumentArray))
} }
/** /**
Initializes a `Where` clause that compares equality Initializes a `Where` clause that compares equality
- parameter keyPath: the keyPath to compare with - parameter keyPath: the keyPath to compare with
- parameter value: the arguments for the `==` operator - parameter value: the arguments for the `==` operator
*/ */
public init(_ keyPath: KeyPath, isEqualTo value: NSObject?) { public init(_ keyPath: KeyPath, isEqualTo value: NSObject?) {
self.init(value == nil self.init(value == nil
@@ -116,22 +114,22 @@ public struct Where: FetchClause, QueryClause, DeleteClause {
} }
/** /**
Initializes a `Where` clause that compares membership Initializes a `Where` clause that compares membership
- parameter keyPath: the keyPath to compare with - parameter keyPath: the keyPath to compare with
- parameter list: the array to check membership of - parameter list: the array to check membership of
*/ */
public init(_ keyPath: KeyPath, isMemberOf list: NSArray) { public init(_ keyPath: KeyPath, isMemberOf list: NSArray) {
self.init(NSPredicate(format: "\(keyPath) IN %@", list)) self.init(NSPredicate(format: "\(keyPath) IN %@", list))
} }
/** /**
Initializes a `Where` clause that compares membership Initializes a `Where` clause that compares membership
- parameter keyPath: the keyPath to compare with - parameter keyPath: the keyPath to compare with
- parameter list: the sequence to check membership of - parameter list: the sequence to check membership of
*/ */
public init<S: SequenceType where S.Generator.Element: NSObject>(_ keyPath: KeyPath, isMemberOf list: S) { public init<S: SequenceType where S.Generator.Element: NSObject>(_ keyPath: KeyPath, isMemberOf list: S) {
self.init(NSPredicate(format: "\(keyPath) IN %@", Array(list) as NSArray)) self.init(NSPredicate(format: "\(keyPath) IN %@", Array(list) as NSArray))
@@ -144,7 +142,7 @@ public struct Where: FetchClause, QueryClause, DeleteClause {
public func applyToFetchRequest(fetchRequest: NSFetchRequest) { public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.predicate != nil { if let predicate = fetchRequest.predicate where predicate != self.predicate {
CoreStore.log( CoreStore.log(
.Warning, .Warning,

View File

@@ -31,14 +31,12 @@ import CoreData
public extension CoreStore { public extension CoreStore {
// MARK: Public
/** /**
Using the `defaultStack`, fetches the `NSManagedObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context. Using the `defaultStack`, fetches the `NSManagedObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context.
- parameter object: a reference to the object created/fetched outside the `DataStack` - parameter object: a reference to the object created/fetched outside the `DataStack`
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public static func fetchExisting<T: NSManagedObject>(object: T) -> T? { public static func fetchExisting<T: NSManagedObject>(object: T) -> T? {
@@ -46,11 +44,11 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObject` instance in the `DataStack`'s context from an `NSManagedObjectID`. Using the `defaultStack`, fetches the `NSManagedObject` instance in the `DataStack`'s context from an `NSManagedObjectID`.
- parameter objectID: the `NSManagedObjectID` for the object - parameter objectID: the `NSManagedObjectID` for the object
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public static func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? { public static func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
@@ -58,11 +56,11 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context. Using the `defaultStack`, fetches the `NSManagedObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context.
- parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack` - parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack`
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
@warn_unused_result @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: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
@@ -70,11 +68,11 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`. Using the `defaultStack`, fetches the `NSManagedObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`.
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
@warn_unused_result @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: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
@@ -82,12 +80,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -95,12 +93,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -108,12 +106,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -121,12 +119,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -134,12 +132,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -147,12 +145,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -160,12 +158,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -173,12 +171,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -186,12 +184,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -199,12 +197,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Using the `defaultStack`, fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -212,15 +210,15 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Using the `defaultStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -228,15 +226,15 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Using the `defaultStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -244,15 +242,15 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, queries a dictionary of attribtue values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Using the `defaultStack`, queries a dictionary of attribtue values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {
@@ -260,15 +258,15 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Using the `defaultStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {

View File

@@ -34,14 +34,12 @@ import CoreData
public extension DataStack { public extension DataStack {
// MARK: Public
/** /**
Fetches the `NSManagedObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context. Fetches the `NSManagedObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context.
- parameter object: a reference to the object created/fetched outside the `DataStack` - parameter object: a reference to the object created/fetched outside the `DataStack`
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject>(object: T) -> T? { public func fetchExisting<T: NSManagedObject>(object: T) -> T? {
@@ -56,11 +54,11 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObject` instance in the `DataStack`'s context from an `NSManagedObjectID`. Fetches the `NSManagedObject` instance in the `DataStack`'s context from an `NSManagedObjectID`.
- parameter objectID: the `NSManagedObjectID` for the object - parameter objectID: the `NSManagedObjectID` for the object
- returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found. - returns: the `NSManagedObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? { public func fetchExisting<T: NSManagedObject>(objectID: NSManagedObjectID) -> T? {
@@ -75,11 +73,11 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context. Fetches the `NSManagedObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context.
- parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack` - parameter objects: an array of `NSManagedObject`s created/fetched outside the `DataStack`
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == T>(objects: S) -> [T] {
@@ -87,11 +85,11 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`. Fetches the `NSManagedObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`.
- parameter objectIDs: the `NSManagedObjectID` array for the objects - parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the `DataStack` - returns: the `NSManagedObject` array for objects that exists in the `DataStack`
*/ */
@warn_unused_result @warn_unused_result
public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] { public func fetchExisting<T: NSManagedObject, S: SequenceType where S.Generator.Element == NSManagedObjectID>(objectIDs: S) -> [T] {
@@ -99,12 +97,12 @@ public extension DataStack {
} }
/** /**
Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -117,12 +115,12 @@ public extension DataStack {
} }
/** /**
Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the first `NSManagedObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s - returns: the first `NSManagedObject` instance that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -135,12 +133,12 @@ public extension DataStack {
} }
/** /**
Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -153,12 +151,12 @@ public extension DataStack {
} }
/** /**
Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches all `NSManagedObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s - returns: all `NSManagedObject` instances that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -171,12 +169,12 @@ public extension DataStack {
} }
/** /**
Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -189,12 +187,12 @@ public extension DataStack {
} }
/** /**
Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the number of `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the number `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -207,12 +205,12 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -225,12 +223,12 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s - returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `FetchClause`s
*/ */
@warn_unused_result @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? {
@@ -243,12 +241,12 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -261,12 +259,12 @@ public extension DataStack {
} }
/** /**
Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s - returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `FetchClause`s
*/ */
@warn_unused_result @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]? {
@@ -279,15 +277,15 @@ public extension DataStack {
} }
/** /**
Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -300,15 +298,15 @@ public extension DataStack {
} }
/** /**
Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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? {
@@ -321,15 +319,15 @@ public extension DataStack {
} }
/** /**
Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {
@@ -342,15 +340,15 @@ public extension DataStack {
} }
/** /**
Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type - parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - 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 @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]]? {

View File

@@ -29,6 +29,9 @@ import CoreData
// MARK: - FetchClause // MARK: - FetchClause
/**
The `FetchClause` implement clauses used to configure `NSFetchRequest`s.
*/
public protocol FetchClause { public protocol FetchClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest) func applyToFetchRequest(fetchRequest: NSFetchRequest)
@@ -37,6 +40,9 @@ public protocol FetchClause {
// MARK: - QueryClause // MARK: - QueryClause
/**
The `QueryClause` implement clauses used to configure `NSFetchRequest`s.
*/
public protocol QueryClause { public protocol QueryClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest) func applyToFetchRequest(fetchRequest: NSFetchRequest)
@@ -45,6 +51,9 @@ public protocol QueryClause {
// MARK: - DeleteClause // MARK: - DeleteClause
/**
The `DeleteClause` implement clauses used to configure `NSFetchRequest`s.
*/
public protocol DeleteClause { public protocol DeleteClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest) func applyToFetchRequest(fetchRequest: NSFetchRequest)

View File

@@ -31,15 +31,13 @@ import CoreData
public extension BaseDataTransaction { public extension BaseDataTransaction {
// MARK: Public
/** /**
Creates an `ImportableObject` by importing from the specified import source. Creates an `ImportableObject` by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from - parameter source: the object to import values from
- returns: the created `ImportableObject` instance, or `nil` if the import was ignored - returns: the created `ImportableObject` instance, or `nil` if the import was ignored
*/ */
public func importObject<T where T: NSManagedObject, T: ImportableObject>( public func importObject<T where T: NSManagedObject, T: ImportableObject>(
into: Into<T>, into: Into<T>,
source: T.ImportSource) throws -> T? { source: T.ImportSource) throws -> T? {
@@ -63,12 +61,12 @@ public extension BaseDataTransaction {
} }
/** /**
Creates multiple `ImportableObject`s by importing from the specified array of import sources. Creates multiple `ImportableObject`s by importing from the specified array of import sources.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from - parameter sourceArray: the array of objects to import values from
- returns: the array of created `ImportableObject` instances - returns: the array of created `ImportableObject` instances
*/ */
public func importObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableObject, S.Generator.Element == T.ImportSource>( public func importObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableObject, S.Generator.Element == T.ImportSource>(
into: Into<T>, into: Into<T>,
sourceArray: S) throws -> [T] { sourceArray: S) throws -> [T] {
@@ -98,12 +96,12 @@ public extension BaseDataTransaction {
} }
/** /**
Updates an existing `ImportableUniqueObject` or creates a new instance by importing from the specified import source. Updates an existing `ImportableUniqueObject` or creates a new instance by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from - parameter source: the object to import values from
- returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored - returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored
*/ */
public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>( public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>(
into: Into<T>, into: Into<T>,
source: T.ImportSource) throws -> T? { source: T.ImportSource) throws -> T? {
@@ -124,7 +122,7 @@ public extension BaseDataTransaction {
if let object = self.fetchOne(From(T), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) { if let object = self.fetchOne(From(T), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) {
guard T.shouldUpdateFromImportSource(source, inTransaction: self) else { guard T.shouldUpdateFromImportSource(source, inTransaction: self) else {
return nil return nil
} }
@@ -147,13 +145,13 @@ public extension BaseDataTransaction {
} }
/** /**
Updates existing `ImportableUniqueObject`s or creates them by importing from the specified array of import sources. Updates existing `ImportableUniqueObject`s or creates them by importing from the specified array of import sources.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from - parameter sourceArray: the array of objects to import values from
- parameter preProcess: a closure that lets the caller tweak the internal `UniqueIDType`-to-`ImportSource` mapping to be used for importing. Callers can remove from/add to/update `mapping` and return the updated array from the closure. - parameter preProcess: a closure that lets the caller tweak the internal `UniqueIDType`-to-`ImportSource` mapping to be used for importing. Callers can remove from/add to/update `mapping` and return the updated array from the closure.
- returns: the array of created/updated `ImportableUniqueObject` instances - returns: the array of created/updated `ImportableUniqueObject` instances
*/ */
public func importUniqueObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableUniqueObject, S.Generator.Element == T.ImportSource>( public func importUniqueObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableUniqueObject, S.Generator.Element == T.ImportSource>(
into: Into<T>, into: Into<T>,
sourceArray: S, sourceArray: S,

View File

@@ -30,44 +30,45 @@ import CoreData
// MARK: - ImportableObject // MARK: - ImportableObject
/** /**
`NSManagedObject` subclasses that conform to the `ImportableObject` protocol can be imported from a specified `ImportSource`. This allows transactions to create and insert instances this way: `NSManagedObject` subclasses that conform to the `ImportableObject` protocol can be imported from a specified `ImportSource`. This allows transactions to create and insert instances this way:
```
class MyPersonEntity: NSManagedObject, ImportableObject { class MyPersonEntity: NSManagedObject, ImportableObject {
typealias ImportSource = NSDictionary typealias ImportSource = NSDictionary
// ... // ...
} }
CoreStore.beginAsynchronous { (transaction) -> Void in CoreStore.beginAsynchronous { (transaction) -> Void in
let json: NSDictionary = // ... let json: NSDictionary = // ...
let person = try! transaction.importObject( let person = try! transaction.importObject(
Into(MyPersonEntity), Into(MyPersonEntity),
source: json source: json
) )
// ... // ...
transaction.commit() transaction.commit()
} }
*/ ```
*/
public protocol ImportableObject: class { public protocol ImportableObject: class {
/** /**
The data type for the import source. This is most commonly an `NSDictionary` or another external source such as an `NSUserDefaults`. The data type for the import source. This is most commonly an `NSDictionary` or another external source such as an `NSUserDefaults`.
*/ */
typealias ImportSource typealias ImportSource
/** /**
Return `true` if an object should be created from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`. Return `true` if an object should be created from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`.
- parameter source: the object to import from - 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. - 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. - 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. 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.
- parameter source: the object to import from - 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. - 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
} }

View File

@@ -30,87 +30,88 @@ import CoreData
// MARK: - ImportableUniqueObject // MARK: - ImportableUniqueObject
/** /**
`NSManagedObject` subclasses that conform to the `ImportableUniqueObject` protocol can be imported from a specified `ImportSource`. This allows transactions to either update existing objects or create new instances this way: `NSManagedObject` subclasses that conform to the `ImportableUniqueObject` protocol can be imported from a specified `ImportSource`. This allows transactions to either update existing objects or create new instances this way:
```
class MyPersonEntity: NSManagedObject, ImportableUniqueObject { class MyPersonEntity: NSManagedObject, ImportableUniqueObject {
typealias ImportSource = NSDictionary typealias ImportSource = NSDictionary
typealias UniqueIDType = NSString typealias UniqueIDType = NSString
// ... // ...
} }
CoreStore.beginAsynchronous { (transaction) -> Void in CoreStore.beginAsynchronous { (transaction) -> Void in
let json: NSDictionary = // ... let json: NSDictionary = // ...
let person = try! transaction.importUniqueObject( let person = try! transaction.importUniqueObject(
Into(MyPersonEntity), Into(MyPersonEntity),
source: json source: json
) )
// ... // ...
transaction.commit() transaction.commit()
} }
*/ ```
*/
public protocol ImportableUniqueObject: ImportableObject { public protocol ImportableUniqueObject: ImportableObject {
/** /**
The data type for the import source. This is most commonly an `NSDictionary` or another external source such as an `NSUserDefaults`. The data type for the import source. This is most commonly an `NSDictionary` or another external source such as an `NSUserDefaults`.
*/ */
typealias ImportSource typealias ImportSource
/** /**
The data type for the entity's unique ID attribute The data type for the entity's unique ID attribute
*/ */
typealias UniqueIDType: NSObject typealias UniqueIDType: NSObject
/** /**
The keyPath to the entity's unique ID attribute The keyPath to the entity's unique ID attribute
*/ */
static var uniqueIDKeyPath: String { get } static var uniqueIDKeyPath: String { get }
/** /**
The object's unique ID value The object's unique ID value
*/ */
var uniqueIDValue: UniqueIDType { get set } var uniqueIDValue: UniqueIDType { get set }
/** /**
Return `true` if an object should be created from `source`. Return `false` to ignore and skip `source`. The default implementation returns the value returned by the `shouldUpdateFromImportSource(:inTransaction:)` implementation. Return `true` if an object should be created from `source`. Return `false` to ignore and skip `source`. The default implementation returns the value returned by the `shouldUpdateFromImportSource(:inTransaction:)` implementation.
- parameter source: the object to import from - 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. - 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. - 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`. Return `true` if an object should be updated from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`.
- parameter source: the object to import from - 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. - 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. - 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. 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.
- parameter source: the object to import from - 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. - 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`. - 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(...)`. 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(...)`.
- parameter source: the object to import from - 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. - 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. 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.
- parameter source: the object to import from - 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. - 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
} }

View File

@@ -30,8 +30,6 @@ import Foundation
public extension CoreStore { public extension CoreStore {
// MARK: Public
/** /**
The `CoreStoreLogger` instance to be used. The default logger is an instance of a `DefaultLogger`. The `CoreStoreLogger` instance to be used. The default logger is an instance of a `DefaultLogger`.
*/ */

View File

@@ -29,8 +29,8 @@ import Foundation
// MARK: - LogLevel // MARK: - LogLevel
/** /**
The `LogLevel` indicates the severity of a log message. The `LogLevel` indicates the severity of a log message.
*/ */
public enum LogLevel { public enum LogLevel {
case Trace case Trace
@@ -43,41 +43,41 @@ public enum LogLevel {
// MARK: - CoreStoreLogger // MARK: - CoreStoreLogger
/** /**
Custom loggers should implement the `CoreStoreLogger` protocol and pass its instance to `CoreStore.logger`. Calls to `log(...)`, `handleError(...)`, and `assert(...)` are not tied to a specific queue/thread, so it is the implementer's job to handle thread-safety. Custom loggers should implement the `CoreStoreLogger` protocol and pass its instance to `CoreStore.logger`. Calls to `log(...)`, `handleError(...)`, and `assert(...)` are not tied to a specific queue/thread, so it is the implementer's job to handle thread-safety.
*/ */
public protocol CoreStoreLogger { public protocol CoreStoreLogger {
/** /**
Handles log messages sent by the `CoreStore` framework. Handles log messages sent by the `CoreStore` framework.
:level: the severity of the log message :level: the severity of the log message
:message: the log message :message: the log message
:fileName: the source file name :fileName: the source file name
:lineNumber: the source line number :lineNumber: the source line number
:functionName: the source function name :functionName: the source function name
*/ */
func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
/** /**
Handles errors sent by the `CoreStore` framework. Handles errors sent by the `CoreStore` framework.
:error: the error :error: the error
:message: the error message :message: the error message
:fileName: the source file name :fileName: the source file name
:lineNumber: the source line number :lineNumber: the source line number
:functionName: the source function name :functionName: the source function name
*/ */
func handleError(error error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) func handleError(error error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
/** /**
Handles assertions made throughout the `CoreStore` framework. Handles assertions made throughout the `CoreStore` framework.
:condition: the assertion condition :condition: the assertion condition
:message: the assertion message :message: the assertion message
:fileName: the source file name :fileName: the source file name
:lineNumber: the source line number :lineNumber: the source line number
:functionName: the source function name :functionName: the source function name
*/ */
func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)
} }
@@ -101,6 +101,5 @@ internal func typeName(value: AnyClass) -> String {
internal func typeName(name: String?) -> String { internal func typeName(name: String?) -> String {
let typeName = name ?? "unknown" return "<\(name ?? "unknown")>"
return "<\(typeName)>"
} }

View File

@@ -29,12 +29,12 @@ import Foundation
// MARK: - DefaultLogger // MARK: - DefaultLogger
/** /**
The `DefaultLogger` is a basic implementation of the `CoreStoreLogger` protocol. The `DefaultLogger` is a basic implementation of the `CoreStoreLogger` protocol.
- The `log(...)` method calls `print(...)` to print the level, source file name, line number, function name, and the log message. - The `log(...)` method calls `print(...)` to print the level, source file name, line number, function name, and the log message.
- The `handleError(...)` method calls `print(...)` to print the source file name, line number, function name, and the error message. - The `handleError(...)` method calls `print(...)` to print the source file name, line number, function name, and the error message.
- The `assert(...)` method calls `assert(...)` on the arguments. - The `assert(...)` method calls `assert(...)` on the arguments.
*/ */
public final class DefaultLogger: CoreStoreLogger { public final class DefaultLogger: CoreStoreLogger {
public init() { } public init() { }

View File

@@ -35,15 +35,15 @@ import CoreData
public extension CoreStore { public extension CoreStore {
/** /**
Asynchronously adds to the `defaultStack` an SQLite store from the given SQLite file name. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.) Asynchronously adds to the `defaultStack` an SQLite store from the given SQLite file name. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public static func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? { 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( return try self.defaultStack.addSQLiteStore(
@@ -56,15 +56,15 @@ public extension CoreStore {
} }
/** /**
Asynchronously adds to the `defaultStack` an SQLite store from the given SQLite file URL. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.) Asynchronously adds to the `defaultStack` an SQLite store from the given SQLite file URL. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public static func addSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? { public static func addSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.addSQLiteStore( return try self.defaultStack.addSQLiteStore(
@@ -77,14 +77,14 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, migrates an SQLite store with the specified filename to the `DataStack`'s managed object model version WITHOUT adding the migrated store to the data stack. Using the `defaultStack`, migrates an SQLite store with the specified filename to the `DataStack`'s managed object model version WITHOUT adding the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public static func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? { public static func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.upgradeSQLiteStoreIfNeeded( return try self.defaultStack.upgradeSQLiteStoreIfNeeded(
@@ -96,14 +96,14 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, migrates an SQLite store at the specified file URL and configuration name to the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack. Using the `defaultStack`, migrates an SQLite store at the specified file URL and configuration name to the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public static func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? { public static func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.defaultStack.upgradeSQLiteStoreIfNeeded( return try self.defaultStack.upgradeSQLiteStoreIfNeeded(
@@ -115,13 +115,13 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, checks for the required migrations needed for the store with the specified filename and configuration to be migrated to the `DataStack`'s managed object model version. This method throws an error if the store does not exist, if inspection of the store failed, or no mapping model was found/inferred. Using the `defaultStack`, checks for the required migrations needed for the store with the specified filename and configuration to be migrated to the `DataStack`'s managed object model version. This method throws an error if the store does not exist, if inspection of the store failed, or no mapping model was found/inferred.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: an array of `MigrationType`s indicating the chain of migrations required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed. :return: an array of `MigrationType`s indicating the chain of migrations required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/ */
@warn_unused_result @warn_unused_result
public static func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] { public static func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
@@ -133,13 +133,13 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, checks if the store at the specified file URL and configuration needs to be migrated to the `DataStack`'s managed object model version. Using the `defaultStack`, checks if the store at the specified file URL and configuration needs to be migrated to the `DataStack`'s managed object model version.
- parameter fileURL: the local file URL for the SQLite persistent store. - parameter fileURL: the local file URL for the SQLite persistent store.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: a `MigrationType` indicating the type of migration required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed. :return: a `MigrationType` indicating the type of migration required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/ */
@warn_unused_result @warn_unused_result
public static func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] { public static func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {

View File

@@ -35,11 +35,11 @@ import CoreData
public extension DataStack { public extension DataStack {
/** /**
Asynchronously adds an in-memory store to the stack. Asynchronously adds an in-memory store to the stack.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result.
*/ */
public func addInMemoryStore(configuration configuration: String? = nil, completion: (PersistentStoreResult) -> Void) { public func addInMemoryStore(configuration configuration: String? = nil, completion: (PersistentStoreResult) -> Void) {
self.coordinator.performBlock { self.coordinator.performBlock {
@@ -76,15 +76,15 @@ public extension DataStack {
} }
/** /**
Asynchronously adds to the stack an SQLite store from the given SQLite file name. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.) Asynchronously adds to the stack an SQLite store from the given SQLite file name. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? { public func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return try self.addSQLiteStore( return try self.addSQLiteStore(
@@ -100,15 +100,15 @@ public extension DataStack {
} }
/** /**
Asynchronously adds to the stack an SQLite store from the given SQLite file URL. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.) Asynchronously adds to the stack an SQLite store from the given SQLite file URL. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously. - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public func addSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? { public func addSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
CoreStore.assert( CoreStore.assert(
@@ -231,14 +231,14 @@ public extension DataStack {
} }
/** /**
Migrates an SQLite store with the specified filename to the `DataStack`'s managed object model version WITHOUT adding the migrated store to the data stack. Migrates an SQLite store with the specified filename to the `DataStack`'s managed object model version WITHOUT adding the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? { public func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.upgradeSQLiteStoreIfNeeded( return try self.upgradeSQLiteStoreIfNeeded(
@@ -253,14 +253,14 @@ public extension DataStack {
} }
/** /**
Migrates an SQLite store at the specified file URL and configuration name to the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack. Migrates an SQLite store at the specified file URL and configuration name to the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`. - parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required - returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/ */
public func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? { public func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
let metadata: [String: AnyObject] let metadata: [String: AnyObject]
@@ -291,13 +291,13 @@ public extension DataStack {
} }
/** /**
Checks for the required migrations needed for the store with the specified filename and configuration to be migrated to the `DataStack`'s managed object model version. This method throws an error if the store does not exist, if inspection of the store failed, or no mapping model was found/inferred. Checks for the required migrations needed for the store with the specified filename and configuration to be migrated to the `DataStack`'s managed object model version. This method throws an error if the store does not exist, if inspection of the store failed, or no mapping model was found/inferred.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: an array of `MigrationType`s indicating the chain of migrations required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed. :return: an array of `MigrationType`s indicating the chain of migrations required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/ */
@warn_unused_result @warn_unused_result
public func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] { public func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
@@ -312,13 +312,13 @@ public extension DataStack {
} }
/** /**
Checks if the store at the specified file URL and configuration needs to be migrated to the `DataStack`'s managed object model version. Checks if the store at the specified file URL and configuration needs to be migrated to the `DataStack`'s managed object model version.
- parameter fileURL: the local file URL for the SQLite persistent store. - parameter fileURL: the local file URL for the SQLite persistent store.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`. - parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: a `MigrationType` indicating the type of migration required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed. :return: a `MigrationType` indicating the type of migration required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/ */
@warn_unused_result @warn_unused_result
public func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] { public func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {

View File

@@ -30,36 +30,36 @@ import CoreData
// MARK: - MigrationChain // MARK: - MigrationChain
/** /**
A `MigrationChain` indicates the sequence of model versions to be used as the order for incremental migration. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants. A `MigrationChain` indicates the sequence of model versions to be used as the order for incremental migration. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants.
Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable incremental migrations: Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable incremental migrations:
```
let dataStack = DataStack(migrationChain: nil) let dataStack = DataStack(migrationChain: nil)
```
This means that the mapping model will be computed from the store's version straight to the `DataStack`'s model version. This means that the mapping model will be computed from the store's version straight to the `DataStack`'s model version.
To support incremental migrations, specify the linear order of versions: To support incremental migrations, specify the linear order of versions:
```
let dataStack = DataStack(migrationChain: let dataStack = DataStack(migrationChain:
["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"]) ["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"])
```
or for more complex migration paths, a version tree that maps the key-values to the source-destination versions: or for more complex migration paths, a version tree that maps the key-values to the source-destination versions:
```
let dataStack = DataStack(migrationChain: [ let dataStack = DataStack(migrationChain: [
"MyAppModel": "MyAppModelV3", "MyAppModel": "MyAppModelV3",
"MyAppModelV2": "MyAppModelV4", "MyAppModelV2": "MyAppModelV4",
"MyAppModelV3": "MyAppModelV4" "MyAppModelV3": "MyAppModelV4"
]) ])
```
This allows for different migration paths depending on the starting version. The example above resolves to the following paths: This allows for different migration paths depending on the starting version. The example above resolves to the following paths:
- MyAppModel-MyAppModelV3-MyAppModelV4 - MyAppModel-MyAppModelV3-MyAppModelV4
- MyAppModelV2-MyAppModelV4 - MyAppModelV2-MyAppModelV4
- MyAppModelV3-MyAppModelV4 - MyAppModelV3-MyAppModelV4
The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met: The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met:
- a version appears twice in an array - a version appears twice in an array
- a version appears twice as a key in a dictionary literal - a version appears twice as a key in a dictionary literal
- a loop is found in any of the paths - a loop is found in any of the paths
*/ */
public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible { public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible {
// MARK: NilLiteralConvertible // MARK: NilLiteralConvertible

View File

@@ -29,46 +29,44 @@ import Foundation
// MARK: - MigrationResult // MARK: - MigrationResult
/** /**
The `MigrationResult` indicates the result of a migration. The `MigrationResult` indicates the result of a migration.
The `MigrationResult` can be treated as a boolean: The `MigrationResult` can be treated as a boolean:
```
CoreStore.upgradeSQLiteStoreIfNeeded { transaction in CoreStore.upgradeSQLiteStoreIfNeeded { transaction in
// ... // ...
let result = transaction.commit() let result = transaction.commit()
if result { if result {
// succeeded // succeeded
} }
else { else {
// failed // failed
} }
} }
```
or as an `enum`, where the resulting associated object can also be inspected: or as an `enum`, where the resulting associated object can also be inspected:
```
CoreStore.beginAsynchronous { transaction in CoreStore.beginAsynchronous { transaction in
// ... // ...
let result = transaction.commit() let result = transaction.commit()
switch result { switch result {
case .Success(let hasChanges): case .Success(let hasChanges):
// hasChanges indicates if there were changes or not // hasChanges indicates if there were changes or not
case .Failure(let error): case .Failure(let error):
// error is the NSError instance for the failure // error is the NSError instance for the failure
} }
} }
``` ```
*/ */
public enum MigrationResult { public enum MigrationResult {
// MARK: Public
/** /**
`MigrationResult.Success` indicates either the migration succeeded, or there were no migrations needed. The associated value is an array of `MigrationType`s reflecting the migration steps completed. `MigrationResult.Success` indicates either the migration succeeded, or there were no migrations needed. The associated value is an array of `MigrationType`s reflecting the migration steps completed.
*/ */
case Success([MigrationType]) case Success([MigrationType])
/** /**
`SaveResult.Failure` indicates that the migration failed. The associated object for this value is the related `NSError` instance. `SaveResult.Failure` indicates that the migration failed. The associated object for this value is the related `NSError` instance.
*/ */
case Failure(NSError) case Failure(NSError)
@@ -103,6 +101,7 @@ extension MigrationResult: BooleanType {
public var boolValue: Bool { public var boolValue: Bool {
switch self { switch self {
case .Success: return true case .Success: return true
case .Failure: return false case .Failure: return false
} }

View File

@@ -29,30 +29,28 @@ import Foundation
// MARK: - MigrationType // MARK: - MigrationType
/** /**
The `MigrationType` specifies the type of migration required for a store. The `MigrationType` specifies the type of migration required for a store.
*/ */
public enum MigrationType: BooleanType { public enum MigrationType: BooleanType {
// MARK: Public
/** /**
Indicates that the persistent store matches the latest model version and no migration is needed Indicates that the persistent store matches the latest model version and no migration is needed
*/ */
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 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 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`. Returns the source model version for the migration type. If no migration is required, `sourceVersion` will be equal to the `destinationVersion`.
*/ */
public var sourceVersion: String { public var sourceVersion: String {
switch self { switch self {
@@ -69,8 +67,8 @@ public enum MigrationType: BooleanType {
} }
/** /**
Returns the destination model version for the migration type. If no migration is required, `destinationVersion` will be equal to the `sourceVersion`. Returns the destination model version for the migration type. If no migration is required, `destinationVersion` will be equal to the `sourceVersion`.
*/ */
public var destinationVersion: String { public var destinationVersion: String {
switch self { switch self {
@@ -87,8 +85,8 @@ public enum MigrationType: BooleanType {
} }
/** /**
Returns `true` if the `MigrationType` is a lightweight migration. Used as syntactic sugar. Returns `true` if the `MigrationType` is a lightweight migration. Used as syntactic sugar.
*/ */
public var isLightweightMigration: Bool { public var isLightweightMigration: Bool {
if case .Lightweight = self { if case .Lightweight = self {
@@ -99,8 +97,8 @@ public enum MigrationType: BooleanType {
} }
/** /**
Returns `true` if the `MigrationType` is a heavyweight migration. Used as syntactic sugar. Returns `true` if the `MigrationType` is a heavyweight migration. Used as syntactic sugar.
*/ */
public var isHeavyweightMigration: Bool { public var isHeavyweightMigration: Bool {
if case .Heavyweight = self { if case .Heavyweight = self {

View File

@@ -26,45 +26,48 @@
import Foundation import Foundation
import CoreData import CoreData
// MARK: - CoreStoreError
/** /**
The `NSError` error domain for `CoreStore`. The `NSError` error domain for `CoreStore`.
*/ */
public let CoreStoreErrorDomain = "com.corestore.error" public let CoreStoreErrorDomain = "com.corestore.error"
/** /**
The `NSError` error codes for `CoreStoreErrorDomain`. The `NSError` error codes for `CoreStoreErrorDomain`.
*/ */
public enum CoreStoreErrorCode: Int { public enum CoreStoreErrorCode: Int {
/** /**
A failure occured because of an unknown error. 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`. The `NSPersistentStore` could note be initialized because another store existed at the specified `NSURL`.
*/ */
case DifferentPersistentStoreExistsAtURL case DifferentPersistentStoreExistsAtURL
/** /**
The `NSPersistentStore` specified could not be found. The `NSPersistentStore` specified could not be found.
*/ */
case PersistentStoreNotFound case PersistentStoreNotFound
/** /**
An `NSMappingModel` could not be found for a specific source and destination model versions. An `NSMappingModel` could not be found for a specific source and destination model versions.
*/ */
case MappingModelNotFound case MappingModelNotFound
} }
// MARK: - NSError+CoreStore // MARK: - NSError
public extension NSError { public extension NSError {
/** /**
If the error's domain is equal to `CoreStoreErrorDomain`, returns the associated `CoreStoreErrorCode`. For other domains, returns `nil`. If the error's domain is equal to `CoreStoreErrorDomain`, returns the associated `CoreStoreErrorCode`. For other domains, returns `nil`.
*/ */
public var coreStoreErrorCode: CoreStoreErrorCode? { public var coreStoreErrorCode: CoreStoreErrorCode? {
return (self.domain == CoreStoreErrorDomain return (self.domain == CoreStoreErrorDomain

View File

@@ -32,14 +32,12 @@ import CoreData
@available(OSX, unavailable) @available(OSX, unavailable)
public extension CoreStore { public extension CoreStore {
// MARK: Public
/** /**
Using the `defaultStack`, creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`. Using the `defaultStack`, creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`.
- parameter object: the `NSManagedObject` to observe changes from - parameter object: the `NSManagedObject` to observe changes from
- returns: a `ObjectMonitor` that monitors changes to `object` - returns: a `ObjectMonitor` that monitors changes to `object`
*/ */
@warn_unused_result @warn_unused_result
public static func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> { public static func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {
@@ -47,11 +45,11 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Using the `defaultStack`, creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @warn_unused_result
public static func monitorList<T: NSManagedObject>(from: From<T>, _ queryClauses: FetchClause...) -> ListMonitor<T> { public static func monitorList<T: NSManagedObject>(from: From<T>, _ queryClauses: FetchClause...) -> ListMonitor<T> {
@@ -60,12 +58,12 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Using the `defaultStack`, creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @warn_unused_result
public static func monitorList<T: NSManagedObject>(from: From<T>, _ queryClauses: [FetchClause]) -> ListMonitor<T> { public static func monitorList<T: NSManagedObject>(from: From<T>, _ queryClauses: [FetchClause]) -> ListMonitor<T> {
@@ -97,13 +95,13 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Using the `defaultStack`, creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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> {
@@ -111,13 +109,13 @@ public extension CoreStore {
} }
/** /**
Using the `defaultStack`, creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Using the `defaultStack`, creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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> {

View File

@@ -35,14 +35,12 @@ import CoreData
@available(OSX, unavailable) @available(OSX, unavailable)
public extension DataStack { public extension DataStack {
// MARK: Public
/** /**
Creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`. Creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`.
- parameter object: the `NSManagedObject` to observe changes from - parameter object: the `NSManagedObject` to observe changes from
- returns: a `ObjectMonitor` that monitors changes to `object` - returns: a `ObjectMonitor` that monitors changes to `object`
*/ */
@warn_unused_result @warn_unused_result
public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> { public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {
@@ -58,11 +56,11 @@ public extension DataStack {
} }
/** /**
Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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> {
@@ -71,11 +69,11 @@ public extension DataStack {
} }
/** /**
Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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> {
@@ -137,26 +135,26 @@ public extension DataStack {
} }
/** /**
Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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) return self.monitorSectionedList(from, sectionBy, fetchClauses)
} }
/** /**
Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type - 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 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. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list - returns: a `ListMonitor` instance that monitors changes to the list
*/ */
@warn_unused_result @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> {

View File

@@ -33,88 +33,88 @@ import CoreData
// MARK: - ListMonitor // MARK: - ListMonitor
/** /**
The `ListMonitor` monitors changes to a list of `NSManagedObject` instances. Observers that implement the `ListObserver` protocol may then register themselves to the `ListMonitor`'s `addObserver(_:)` method: The `ListMonitor` monitors changes to a list of `NSManagedObject` instances. Observers that implement the `ListObserver` protocol may then register themselves to the `ListMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorList( let monitor = CoreStore.monitorList(
From(MyPersonEntity), From(MyPersonEntity),
Where("title", isEqualTo: "Engineer"), Where("title", isEqualTo: "Engineer"),
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
monitor.addObserver(self) monitor.addObserver(self)
```
The `ListMonitor` instance needs to be held on (retained) for as long as the list needs to be observed. The `ListMonitor` instance needs to be held on (retained) for as long as the list needs to be observed.
Observers registered via `addObserver(_:)` are not retained. `ListMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. Observers registered via `addObserver(_:)` are not retained. `ListMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles.
Lists created with `monitorList(...)` keep a single-section list of objects, where each object can be accessed by index: Lists created with `monitorList(...)` keep a single-section list of objects, where each object can be accessed by index:
```
let firstPerson: MyPersonEntity = monitor[0] let firstPerson: MyPersonEntity = monitor[0]
```
Accessing the list with an index above the valid range will throw an exception. Accessing the list with an index above the valid range will throw an exception.
Creating a sectioned-list is also possible with the `monitorSectionedList(...)` method: Creating a sectioned-list is also possible with the `monitorSectionedList(...)` method:
```
let monitor = CoreStore.monitorSectionedList( let monitor = CoreStore.monitorSectionedList(
From(MyPersonEntity), From(MyPersonEntity),
SectionBy("age") { "Age \($0)" }, SectionBy("age") { "Age \($0)" },
Where("title", isEqualTo: "Engineer"), Where("title", isEqualTo: "Engineer"),
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
monitor.addObserver(self) monitor.addObserver(self)
```
Objects from `ListMonitor`s created this way can be accessed either by an `NSIndexPath` or a tuple: Objects from `ListMonitor`s created this way can be accessed either by an `NSIndexPath` or a tuple:
```
let indexPath = NSIndexPath(forItem: 3, inSection: 2) let indexPath = NSIndexPath(forItem: 3, inSection: 2)
let person1 = monitor[indexPath] let person1 = monitor[indexPath]
let person2 = monitor[2, 3] let person2 = monitor[2, 3]
```
In the example above, both `person1` and `person2` will contain the object at section=2, index=3. In the example above, both `person1` and `person2` will contain the object at section=2, index=3.
*/ */
@available(OSX, unavailable) @available(OSX, unavailable)
public final class ListMonitor<T: NSManagedObject> { public final class ListMonitor<T: NSManagedObject> {
// MARK: Public (Accessors) // MARK: Public (Accessors)
/** /**
Returns the object at the given index within the first section. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. Returns the object at the given index within the first section. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`.
- parameter index: the index of the object. Using an index above the valid range will throw an exception. - parameter index: the index of the object. Using an index above the valid range will throw an exception.
- returns: the `NSManagedObject` at the specified index - returns: the `NSManagedObject` at the specified index
*/ */
public subscript(index: Int) -> T { public subscript(index: Int) -> T {
return self[0, index] return self[0, index]
} }
/** /**
Returns the object at the given index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. Returns the object at the given index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`.
- parameter index: the index for the object. Using an index above the valid range will return `nil`. - parameter index: the index for the object. Using an index above the valid range will return `nil`.
- returns: the `NSManagedObject` at the specified index, or `nil` if out of bounds - returns: the `NSManagedObject` at the specified index, or `nil` if out of bounds
*/ */
public subscript(safeIndex index: Int) -> T? { public subscript(safeIndex index: Int) -> T? {
return self[safeSectionIndex: 0, safeItemIndex: index] return self[safeSectionIndex: 0, safeItemIndex: index]
} }
/** /**
Returns the object at the given `sectionIndex` and `itemIndex`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. Returns the object at the given `sectionIndex` and `itemIndex`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`.
- parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will throw an exception. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will throw an exception.
- parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will throw an exception. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will throw an exception.
- returns: the `NSManagedObject` at the specified section and item index - returns: the `NSManagedObject` at the specified section and item index
*/ */
public subscript(sectionIndex: Int, itemIndex: Int) -> T { public subscript(sectionIndex: Int, itemIndex: Int) -> T {
return self[NSIndexPath(indexes: [sectionIndex, itemIndex], length: 2)] return self[NSIndexPath(indexes: [sectionIndex, itemIndex], length: 2)]
} }
/** /**
Returns the object at the given section and item index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. Returns the object at the given section and item index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`.
- parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`.
- parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`.
- returns: the `NSManagedObject` at the specified section and item index, or `nil` if out of bounds - returns: the `NSManagedObject` at the specified section and item index, or `nil` if out of bounds
*/ */
public subscript(safeSectionIndex sectionIndex: Int, safeItemIndex itemIndex: Int) -> T? { public subscript(safeSectionIndex sectionIndex: Int, safeItemIndex itemIndex: Int) -> T? {
CoreStore.assert( CoreStore.assert(
@@ -137,11 +137,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the object at the given `NSIndexPath`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. Returns the object at the given `NSIndexPath`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`.
- parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will throw an exception. - parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will throw an exception.
- returns: the `NSManagedObject` at the specified index path - returns: the `NSManagedObject` at the specified index path
*/ */
public subscript(indexPath: NSIndexPath) -> T { public subscript(indexPath: NSIndexPath) -> T {
CoreStore.assert( CoreStore.assert(
@@ -153,11 +153,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the object at the given `NSIndexPath`, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. Returns the object at the given `NSIndexPath`, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`.
- parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`. - 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 - returns: the `NSManagedObject` at the specified index path, or `nil` if out of bounds
*/ */
public subscript(safeIndexPath indexPath: NSIndexPath) -> T? { public subscript(safeIndexPath indexPath: NSIndexPath) -> T? {
return self[ return self[
@@ -167,10 +167,10 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Checks if the `ListMonitor` has at least one object in any section. Checks if the `ListMonitor` has at least one object in any section.
- returns: `true` if at least one object in any section exists, `false` otherwise - returns: `true` if at least one object in any section exists, `false` otherwise
*/ */
@warn_unused_result @warn_unused_result
public func hasObjects() -> Bool { public func hasObjects() -> Bool {
@@ -178,11 +178,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Checks if the `ListMonitor` has at least one object the specified section. Checks if the `ListMonitor` has at least one object the specified section.
- parameter section: the section index. Using an index outside the valid range will return `false`. - parameter section: the section index. Using an index outside the valid range will return `false`.
- returns: `true` if at least one object in the specified section exists, `false` otherwise - returns: `true` if at least one object in the specified section exists, `false` otherwise
*/ */
@warn_unused_result @warn_unused_result
public func hasObjectsInSection(section: Int) -> Bool { public func hasObjectsInSection(section: Int) -> Bool {
@@ -190,10 +190,10 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns all objects in all sections Returns all objects in all sections
- returns: all objects in all sections - returns: all objects in all sections
*/ */
@warn_unused_result @warn_unused_result
public func objectsInAllSections() -> [T] { public func objectsInAllSections() -> [T] {
@@ -206,11 +206,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns all objects in the specified section Returns all objects in the specified section
- parameter section: the section index. Using an index outside the valid range will throw an exception. - parameter section: the section index. Using an index outside the valid range will throw an exception.
- returns: all objects in the specified section - returns: all objects in the specified section
*/ */
@warn_unused_result @warn_unused_result
public func objectsInSection(section: Int) -> [T] { public func objectsInSection(section: Int) -> [T] {
@@ -223,11 +223,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns all objects in the specified section, or `nil` if out of bounds. Returns all objects in the specified section, or `nil` if out of bounds.
- parameter section: the section index. Using an index outside the valid range will return `nil`. - parameter section: the section index. Using an index outside the valid range will return `nil`.
- returns: all objects in the specified section - returns: all objects in the specified section
*/ */
@warn_unused_result @warn_unused_result
public func objectsInSection(safeSectionIndex section: Int) -> [T]? { public func objectsInSection(safeSectionIndex section: Int) -> [T]? {
@@ -240,10 +240,10 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the number of sections Returns the number of sections
- returns: the number of sections - returns: the number of sections
*/ */
@warn_unused_result @warn_unused_result
public func numberOfSections() -> Int { public func numberOfSections() -> Int {
@@ -256,10 +256,10 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the number of objects in all sections Returns the number of objects in all sections
- returns: the number of objects in all sections - returns: the number of objects in all sections
*/ */
@warn_unused_result @warn_unused_result
public func numberOfObjects() -> Int { public func numberOfObjects() -> Int {
@@ -272,11 +272,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the number of objects in the specified section Returns the number of objects in the specified section
- parameter section: the section index. Using an index outside the valid range will throw an exception. - parameter section: the section index. Using an index outside the valid range will throw an exception.
- returns: the number of objects in the specified section - returns: the number of objects in the specified section
*/ */
@warn_unused_result @warn_unused_result
public func numberOfObjectsInSection(section: Int) -> Int { public func numberOfObjectsInSection(section: Int) -> Int {
@@ -284,11 +284,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the number of objects in the specified section, or `nil` if out of bounds. Returns the number of objects in the specified section, or `nil` if out of bounds.
- parameter section: the section index. Using an index outside the valid range will return `nil`. - parameter section: the section index. Using an index outside the valid range will return `nil`.
- returns: the number of objects in the specified section - returns: the number of objects in the specified section
*/ */
@warn_unused_result @warn_unused_result
public func numberOfObjectsInSection(safeSectionIndex section: Int) -> Int? { public func numberOfObjectsInSection(safeSectionIndex section: Int) -> Int? {
@@ -296,11 +296,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the `NSFetchedResultsSectionInfo` for the specified section Returns the `NSFetchedResultsSectionInfo` for the specified section
- parameter section: the section index. Using an index outside the valid range will throw an exception. - parameter section: the section index. Using an index outside the valid range will throw an exception.
- returns: the `NSFetchedResultsSectionInfo` for the specified section - returns: the `NSFetchedResultsSectionInfo` for the specified section
*/ */
@warn_unused_result @warn_unused_result
public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo { public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo {
@@ -313,11 +313,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if out of bounds. Returns the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if out of bounds.
- parameter section: the section index. Using an index outside the valid range will return `nil`. - parameter section: the section index. Using an index outside the valid range will return `nil`.
- returns: the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if the section index is out of bounds. - returns: the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if the section index is out of bounds.
*/ */
@warn_unused_result @warn_unused_result
public func sectionInfoAtIndex(safeSectionIndex section: Int) -> NSFetchedResultsSectionInfo? { public func sectionInfoAtIndex(safeSectionIndex section: Int) -> NSFetchedResultsSectionInfo? {
@@ -386,11 +386,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. Returns the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
- parameter object: the `NSManagedObject` to search the index of - parameter object: the `NSManagedObject` to search the index of
- returns: the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - returns: the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func indexOf(object: T) -> Int? { public func indexOf(object: T) -> Int? {
@@ -403,11 +403,11 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Returns the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. Returns the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
- parameter object: the `NSManagedObject` to search the index of - parameter object: the `NSManagedObject` to search the index of
- returns: the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - returns: the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found.
*/ */
@warn_unused_result @warn_unused_result
public func indexPathOf(object: T) -> NSIndexPath? { public func indexPathOf(object: T) -> NSIndexPath? {
@@ -423,16 +423,16 @@ public final class ListMonitor<T: NSManagedObject> {
// MARK: Public (Observers) // MARK: Public (Observers)
/** /**
Registers a `ListObserver` to be notified when changes to the receiver's list occur. Registers a `ListObserver` to be notified when changes to the receiver's list occur.
To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: a `ListObserver` to send change notifications to - parameter observer: a `ListObserver` to send change notifications to
*/ */
public func addObserver<U: ListObserver where U.ListEntityType == T>(observer: U) { public func addObserver<U: ListObserver where U.ListEntityType == T>(observer: U) {
CoreStore.assert( CoreStore.assert(
@@ -497,16 +497,16 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Registers a `ListObjectObserver` to be notified when changes to the receiver's list occur. Registers a `ListObjectObserver` to be notified when changes to the receiver's list occur.
To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: a `ListObjectObserver` to send change notifications to - parameter observer: a `ListObjectObserver` to send change notifications to
*/ */
public func addObserver<U: ListObjectObserver where U.ListEntityType == T>(observer: U) { public func addObserver<U: ListObjectObserver where U.ListEntityType == T>(observer: U) {
CoreStore.assert( CoreStore.assert(
@@ -641,16 +641,16 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Registers a `ListSectionObserver` to be notified when changes to the receiver's list occur. Registers a `ListSectionObserver` to be notified when changes to the receiver's list occur.
To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: a `ListSectionObserver` to send change notifications to - parameter observer: a `ListSectionObserver` to send change notifications to
*/ */
public func addObserver<U: ListSectionObserver where U.ListEntityType == T>(observer: U) { public func addObserver<U: ListSectionObserver where U.ListEntityType == T>(observer: U) {
CoreStore.assert( CoreStore.assert(
@@ -737,7 +737,7 @@ public final class ListMonitor<T: NSManagedObject> {
callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in
guard let observer = observer else { guard let observer = observer else {
return return
} }
observer.listMonitor( observer.listMonitor(
@@ -820,12 +820,12 @@ public final class ListMonitor<T: NSManagedObject> {
} }
/** /**
Unregisters a `ListObserver` from receiving notifications for changes to the receiver's list. Unregisters a `ListObserver` from receiving notifications for changes to the receiver's list.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
- parameter observer: a `ListObserver` to unregister notifications to - parameter observer: a `ListObserver` to unregister notifications to
*/ */
public func removeObserver<U: ListObserver where U.ListEntityType == T>(observer: U) { public func removeObserver<U: ListObserver where U.ListEntityType == T>(observer: U) {
CoreStore.assert( CoreStore.assert(
@@ -852,29 +852,29 @@ public final class ListMonitor<T: NSManagedObject> {
// MARK: Public (Refetching) // MARK: Public (Refetching)
/** /**
Returns `true` if a call to `refetch(...)` was made to the `ListMonitor` and is currently waiting for the fetching to complete. Returns `false` otherwise. Returns `true` if a call to `refetch(...)` was made to the `ListMonitor` and is currently waiting for the fetching to complete. Returns `false` otherwise.
*/ */
private(set) public var isPendingRefetch = false private(set) public var isPendingRefetch = false
/** /**
Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes.
`refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes.
- 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. - 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) self.refetch(fetchClauses)
} }
/** /**
Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes.
`refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes.
- 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. - 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]) {
CoreStore.assert( CoreStore.assert(
@@ -939,7 +939,7 @@ public final class ListMonitor<T: NSManagedObject> {
// MARK: Internal // MARK: Internal
internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, fetchClauses: [FetchClause]) { internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, fetchClauses: [FetchClause]) {
self.init( self.init(
context: dataStack.mainContext, context: dataStack.mainContext,
transactionQueue: dataStack.childTransactionQueue, transactionQueue: dataStack.childTransactionQueue,
@@ -1034,7 +1034,7 @@ public final class ListMonitor<T: NSManagedObject> {
closure: { [weak self] (note) -> Void in closure: { [weak self] (note) -> Void in
guard let `self` = self else { guard let `self` = self else {
return return
} }

View File

@@ -30,48 +30,49 @@ import CoreData
// MARK: - ListObserver // MARK: - ListObserver
/** /**
Implement the `ListObserver` protocol to observe changes to a list of `NSManagedObject`s. `ListObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method: Implement the `ListObserver` protocol to observe changes to a list of `NSManagedObject`s. `ListObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorList( let monitor = CoreStore.monitorList(
From(MyPersonEntity), From(MyPersonEntity),
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
monitor.addObserver(self) monitor.addObserver(self)
*/ ```
*/
@available(OSX, unavailable) @available(OSX, unavailable)
public protocol ListObserver: class { public protocol ListObserver: class {
/** /**
The `NSManagedObject` type for the observed list The `NSManagedObject` type for the observed list
*/ */
typealias ListEntityType: NSManagedObject typealias ListEntityType: NSManagedObject
/** /**
Handles processing just before a change to the observed list occurs Handles processing just before a change to the observed list occurs
- parameter monitor: the `ListMonitor` monitoring the list being observed - 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 Handles processing right after a change to the observed list occurs
- parameter monitor: the `ListMonitor` monitoring the object being observed - 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. 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 - 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. 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 - parameter monitor: the `ListMonitor` monitoring the object being observed
*/ */
func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>) func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>)
} }
@@ -82,23 +83,23 @@ public protocol ListObserver: class {
public extension ListObserver { public extension ListObserver {
/** /**
The default implementation does nothing. The default implementation does nothing.
*/ */
func listMonitorWillChange(monitor: ListMonitor<ListEntityType>) { } func listMonitorWillChange(monitor: ListMonitor<ListEntityType>) { }
/** /**
The default implementation does nothing. The default implementation does nothing.
*/ */
func listMonitorDidChange(monitor: ListMonitor<ListEntityType>) { } func listMonitorDidChange(monitor: ListMonitor<ListEntityType>) { }
/** /**
The default implementation does nothing. The default implementation does nothing.
*/ */
func listMonitorWillRefetch(monitor: ListMonitor<ListEntityType>) { } func listMonitorWillRefetch(monitor: ListMonitor<ListEntityType>) { }
/** /**
The default implementation does nothing. The default implementation does nothing.
*/ */
func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>) { } func listMonitorDidRefetch(monitor: ListMonitor<ListEntityType>) { }
} }
@@ -106,52 +107,53 @@ public extension ListObserver {
// MARK: - ListObjectObserver // MARK: - ListObjectObserver
/** /**
Implement the `ListObjectObserver` protocol to observe detailed changes to a list's object. `ListObjectObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method: Implement the `ListObjectObserver` protocol to observe detailed changes to a list's object. `ListObjectObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorList( let monitor = CoreStore.monitorList(
From(MyPersonEntity), From(MyPersonEntity),
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
monitor.addObserver(self) monitor.addObserver(self)
*/ ```
*/
@available(OSX, unavailable) @available(OSX, unavailable)
public protocol ListObjectObserver: ListObserver { public protocol ListObjectObserver: ListObserver {
/** /**
Notifies that an object was inserted to the specified `NSIndexPath` in the list Notifies that an object was inserted to the specified `NSIndexPath` in the list
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter object: the entity type for the inserted object - parameter object: the entity type for the inserted object
- parameter indexPath: the new `NSIndexPath` 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: NSIndexPath)
/** /**
Notifies that an object was deleted from the specified `NSIndexPath` in the list Notifies that an object was deleted from the specified `NSIndexPath` in the list
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter object: the entity type for the deleted object - parameter object: the entity type for the deleted object
- parameter indexPath: the `NSIndexPath` 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: NSIndexPath)
/** /**
Notifies that an object at the specified `NSIndexPath` was updated Notifies that an object at the specified `NSIndexPath` was updated
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter object: the entity type for the updated object - parameter object: the entity type for the updated object
- parameter indexPath: the `NSIndexPath` 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: NSIndexPath)
/** /**
Notifies that an object's index changed Notifies that an object's index changed
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter object: the entity type for the moved object - parameter object: the entity type for the moved object
- parameter fromIndexPath: the previous `NSIndexPath` for the moved object - parameter fromIndexPath: the previous `NSIndexPath` for the moved object
- parameter toIndexPath: the new `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: NSIndexPath, toIndexPath: NSIndexPath)
} }
@@ -162,23 +164,23 @@ public protocol ListObjectObserver: ListObserver {
public extension ListObjectObserver { public extension ListObjectObserver {
/** /**
The default implementation does nothing. 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: NSIndexPath) { }
/** /**
The default implementation does nothing. 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: NSIndexPath) { }
/** /**
The default implementation does nothing. 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: NSIndexPath) { }
/** /**
The default implementation does nothing. 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: NSIndexPath, toIndexPath: NSIndexPath) { }
} }
@@ -186,33 +188,34 @@ public extension ListObjectObserver {
// MARK: - ListSectionObserver // MARK: - ListSectionObserver
/** /**
Implement the `ListSectionObserver` protocol to observe changes to a list's section info. `ListSectionObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method: Implement the `ListSectionObserver` protocol to observe changes to a list's section info. `ListSectionObserver`s may register themselves to a `ListMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorSectionedList( let monitor = CoreStore.monitorSectionedList(
From(MyPersonEntity), From(MyPersonEntity),
SectionBy("age") { "Age \($0)" }, SectionBy("age") { "Age \($0)" },
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
monitor.addObserver(self) monitor.addObserver(self)
*/ ```
*/
@available(OSX, unavailable) @available(OSX, unavailable)
public protocol ListSectionObserver: ListObjectObserver { public protocol ListSectionObserver: ListObjectObserver {
/** /**
Notifies that a section was inserted at the specified index Notifies that a section was inserted at the specified index
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the inserted section - parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the inserted section
- parameter sectionIndex: the new section index for the new 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 Notifies that a section was inserted at the specified index
- parameter monitor: the `ListMonitor` monitoring the list being observed - parameter monitor: the `ListMonitor` monitoring the list being observed
- parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the deleted section - parameter sectionInfo: the `NSFetchedResultsSectionInfo` for the deleted section
- parameter sectionIndex: the previous section index 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)
} }
@@ -224,12 +227,12 @@ public protocol ListSectionObserver: ListObjectObserver {
public extension ListSectionObserver { public extension ListSectionObserver {
/** /**
The default implementation does nothing. 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. 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) { }
} }

View File

@@ -33,47 +33,45 @@ import CoreData
// MARK: - ObjectMonitor // MARK: - ObjectMonitor
/** /**
The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method: The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorObject(object) let monitor = CoreStore.monitorObject(object)
monitor.addObserver(self) monitor.addObserver(self)
```
The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed. The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed.
Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles.
*/ */
@available(OSX, unavailable) @available(OSX, unavailable)
public final class ObjectMonitor<T: NSManagedObject> { public final class ObjectMonitor<T: NSManagedObject> {
// MARK: Public
/** /**
Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted. Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted.
*/ */
public var object: T? { public var object: T? {
return self.fetchedResultsController.fetchedObjects?.first as? T return self.fetchedResultsController.fetchedObjects?.first as? T
} }
/** /**
Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted. Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted.
*/ */
public var isObjectDeleted: Bool { public var isObjectDeleted: Bool {
return self.object?.managedObjectContext == nil return self.object?.managedObjectContext == nil
} }
/** /**
Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made. Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made.
To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers. To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: an `ObjectObserver` to send change notifications to - parameter observer: an `ObjectObserver` to send change notifications to
*/ */
public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) { public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
CoreStore.assert( CoreStore.assert(
@@ -143,12 +141,12 @@ public final class ObjectMonitor<T: NSManagedObject> {
} }
/** /**
Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`. Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
- parameter observer: an `ObjectObserver` to unregister notifications to - 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 == T>(observer: U) {
CoreStore.assert( CoreStore.assert(

View File

@@ -30,42 +30,43 @@ import CoreData
// MARK: - ObjectObserver // MARK: - ObjectObserver
/** /**
Implement the `ObjectObserver` protocol to observe changes to a single `NSManagedObject` instance. `ObjectObserver`s may register themselves to a `ObjectMonitor`'s `addObserver(_:)` method: Implement the `ObjectObserver` protocol to observe changes to a single `NSManagedObject` instance. `ObjectObserver`s may register themselves to a `ObjectMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorObject(object) let monitor = CoreStore.monitorObject(object)
monitor.addObserver(self) monitor.addObserver(self)
*/ ```
*/
@available(OSX, unavailable) @available(OSX, unavailable)
public protocol ObjectObserver: class { public protocol ObjectObserver: class {
/** /**
The `NSManagedObject` type for the observed object The `NSManagedObject` type for the observed object
*/ */
typealias ObjectEntityType: NSManagedObject typealias ObjectEntityType: NSManagedObject
/** /**
Handles processing just before a change to the observed `object` occurs Handles processing just before a change to the observed `object` occurs
- parameter monitor: the `ObjectMonitor` monitoring the object being observed - parameter monitor: the `ObjectMonitor` monitoring the object being observed
- parameter object: the `NSManagedObject` instance 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 Handles processing right after a change to the observed `object` occurs
- parameter monitor: the `ObjectMonitor` monitoring the object being observed - parameter monitor: the `ObjectMonitor` monitoring the object being observed
- parameter object: the `NSManagedObject` instance being observed - 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. - 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 Handles processing right after `object` is deleted
- parameter monitor: the `ObjectMonitor` monitoring the object being observed - parameter monitor: the `ObjectMonitor` monitoring the object being observed
- parameter object: the `NSManagedObject` instance 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)
} }
@@ -76,17 +77,17 @@ public protocol ObjectObserver: class {
public extension ObjectObserver { public extension ObjectObserver {
/** /**
The default implementation does nothing. 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. 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. The default implementation does nothing.
*/ */
func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType) { } func objectMonitor(monitor: ObjectMonitor<ObjectEntityType>, didDeleteObject object: ObjectEntityType) { }
} }

View File

@@ -30,35 +30,34 @@ import CoreData
// MARK: - SectionBy // MARK: - SectionBy
/** /**
The `SectionBy` clause indicates the key path to use to group the `ListMonitor` objects into sections. An optional closure can also be provided to transform the value into an appropriate section name: The `SectionBy` clause indicates the key path to use to group the `ListMonitor` objects into sections. An optional closure can also be provided to transform the value into an appropriate section name:
```
let monitor = CoreStore.monitorSectionedList( let monitor = CoreStore.monitorSectionedList(
From(MyPersonEntity), From(MyPersonEntity),
SectionBy("age") { "Age \($0)" }, SectionBy("age") { "Age \($0)" },
OrderBy(.Ascending("lastName")) OrderBy(.Ascending("lastName"))
) )
*/ ```
*/
@available(OSX, unavailable) @available(OSX, unavailable)
public struct SectionBy { public struct SectionBy {
// MARK: Public
/** /**
Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the key path to use to group the objects into sections - parameter sectionKeyPath: the key path to use to group the objects into sections
*/ */
public init(_ sectionKeyPath: KeyPath) { public init(_ sectionKeyPath: KeyPath) {
self.init(sectionKeyPath, { $0 }) self.init(sectionKeyPath, { $0 })
} }
/** /**
Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section name Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section name
- parameter sectionKeyPath: the key path to use to group the objects into sections - parameter sectionKeyPath: the key path to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section name - parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section name
*/ */
public init(_ sectionKeyPath: KeyPath, _ sectionIndexTransformer: (sectionName: String?) -> String?) { public init(_ sectionKeyPath: KeyPath, _ sectionIndexTransformer: (sectionName: String?) -> String?) {
self.sectionKeyPath = sectionKeyPath self.sectionKeyPath = sectionKeyPath

View File

@@ -35,15 +35,12 @@ import CoreData
@available(OSX, unavailable) @available(OSX, unavailable)
public extension UnsafeDataTransaction { public extension UnsafeDataTransaction {
// MARK: Public
/** /**
Creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`. Creates a `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`.
- parameter object: the `NSManagedObject` to observe changes from - parameter object: the `NSManagedObject` to observe changes from
- returns: a `ObjectMonitor` that monitors changes to `object` - returns: a `ObjectMonitor` that monitors changes to `object`
*/ */
@warn_unused_result @warn_unused_result
public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> { public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> {

View File

@@ -33,17 +33,15 @@ import CoreData
// MARK: - AsynchronousDataTransaction // MARK: - AsynchronousDataTransaction
/** /**
The `AsynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginAsynchronous(_:)`, or from `CoreStore.beginAsynchronous(_:)`. The `AsynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginAsynchronous(_:)`, or from `CoreStore.beginAsynchronous(_:)`.
*/ */
public final class AsynchronousDataTransaction: BaseDataTransaction { public final class AsynchronousDataTransaction: BaseDataTransaction {
// MARK: Public
/** /**
Saves the transaction changes. This method should not be used after the `commit()` method was already called once. Saves the transaction changes. This method should not be used after the `commit()` method was already called once.
- parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block.
*/ */
public func commit(completion: (result: SaveResult) -> Void = { _ in }) { public func commit(completion: (result: SaveResult) -> Void = { _ in }) {
CoreStore.assert( CoreStore.assert(
@@ -68,11 +66,11 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Begins a child transaction synchronously where NSManagedObject creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once. Begins a child transaction synchronously where NSManagedObject creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert( CoreStore.assert(
@@ -94,11 +92,11 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
// MARK: BaseDataTransaction // MARK: BaseDataTransaction
/** /**
Creates a new `NSManagedObject` with the specified entity type. Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration - 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. - 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( CoreStore.assert(
@@ -110,11 +108,11 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once. Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be edited - parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @warn_unused_result
public override func edit<T: NSManagedObject>(object: T?) -> T? { public override func edit<T: NSManagedObject>(object: T?) -> T? {
@@ -127,12 +125,12 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once. Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited - parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @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? {
@@ -145,10 +143,10 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once. Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be deleted - parameter object: the `NSManagedObject` type to be deleted
*/ */
public override func delete(object: NSManagedObject?) { public override func delete(object: NSManagedObject?) {
CoreStore.assert( CoreStore.assert(
@@ -160,12 +158,12 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` type to be deleted - parameter object1: the `NSManagedObject` type to be deleted
- parameter object2: another `NSManagedObject` type to be deleted - parameter object2: another `NSManagedObject` type to be deleted
- parameter objects: other `NSManagedObject`s 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( CoreStore.assert(
@@ -177,10 +175,10 @@ public final class AsynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s type to be deleted - 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: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert( CoreStore.assert(

View File

@@ -33,26 +33,26 @@ import CoreData
// MARK: - BaseDataTransaction // MARK: - BaseDataTransaction
/** /**
The `BaseDataTransaction` is an abstract interface for `NSManagedObject` creates, updates, and deletes. All `BaseDataTransaction` subclasses manage a private `NSManagedObjectContext` which are direct children of the `NSPersistentStoreCoordinator`'s root `NSManagedObjectContext`. This means that all updates are saved first to the persistent store, and then propagated up to the read-only `NSManagedObjectContext`. The `BaseDataTransaction` is an abstract interface for `NSManagedObject` creates, updates, and deletes. All `BaseDataTransaction` subclasses manage a private `NSManagedObjectContext` which are direct children of the `NSPersistentStoreCoordinator`'s root `NSManagedObjectContext`. This means that all updates are saved first to the persistent store, and then propagated up to the read-only `NSManagedObjectContext`.
*/ */
public /*abstract*/ class BaseDataTransaction { public /*abstract*/ class BaseDataTransaction {
// MARK: Object management // MARK: Object management
/** /**
Indicates if the transaction has pending changes Indicates if the transaction has pending changes
*/ */
public var hasChanges: Bool { public var hasChanges: Bool {
return self.context.hasChanges return self.context.hasChanges
} }
/** /**
Creates a new `NSManagedObject` with the specified entity type. Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration - 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. - 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( CoreStore.assert(
@@ -101,11 +101,11 @@ public /*abstract*/ class BaseDataTransaction {
} }
/** /**
Returns an editable proxy of a specified `NSManagedObject`. Returns an editable proxy of a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` type to be edited - parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @warn_unused_result
public func edit<T: NSManagedObject>(object: T?) -> T? { public func edit<T: NSManagedObject>(object: T?) -> T? {
@@ -121,12 +121,12 @@ public /*abstract*/ class BaseDataTransaction {
} }
/** /**
Returns an editable proxy of the object with the specified `NSManagedObjectID`. Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited - parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @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? {
@@ -143,10 +143,10 @@ public /*abstract*/ class BaseDataTransaction {
} }
/** /**
Deletes a specified `NSManagedObject`. Deletes a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` to be deleted - parameter object: the `NSManagedObject` to be deleted
*/ */
public func delete(object: NSManagedObject?) { public func delete(object: NSManagedObject?) {
CoreStore.assert( CoreStore.assert(
@@ -161,22 +161,22 @@ public /*abstract*/ class BaseDataTransaction {
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` to be deleted - parameter object1: the `NSManagedObject` to be deleted
- parameter object2: another `NSManagedObject` to be deleted - parameter object2: another `NSManagedObject` to be deleted
- parameter objects: other `NSManagedObject`s 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 }) self.delete(([object1, object2] + objects).flatMap { $0 })
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted - parameter objects: the `NSManagedObject`s to be deleted
*/ */
public func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) { public func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert( CoreStore.assert(
@@ -205,10 +205,10 @@ public /*abstract*/ class BaseDataTransaction {
// MARK: Inspecting Pending Objects // MARK: Inspecting Pending Objects
/** /**
Returns all pending `NSManagedObject`s that were inserted to the transaction. This method should not be called after the `commit()` method was called. Returns all pending `NSManagedObject`s that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObject`s that were inserted to the transaction. - returns: a `Set` of pending `NSManagedObject`s that were inserted to the transaction.
*/ */
public func insertedObjects() -> Set<NSManagedObject> { public func insertedObjects() -> Set<NSManagedObject> {
CoreStore.assert( CoreStore.assert(

View File

@@ -30,13 +30,11 @@ import Foundation
public extension CoreStore { public extension CoreStore {
// MARK: Public
/** /**
Using the `defaultStack`, begins a transaction asynchronously where `NSManagedObject` creates, updates, and deletes can be made. Using the `defaultStack`, begins a transaction asynchronously where `NSManagedObject` creates, updates, and deletes can be made.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
public static func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) { public static func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) {
self.defaultStack.beginAsynchronous(closure) self.defaultStack.beginAsynchronous(closure)

View File

@@ -34,13 +34,11 @@ import CoreData
public extension DataStack { public extension DataStack {
// MARK: Public
/** /**
Begins a transaction asynchronously where `NSManagedObject` creates, updates, and deletes can be made. Begins a transaction asynchronously where `NSManagedObject` creates, updates, and deletes can be made.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
*/ */
public func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) { public func beginAsynchronous(closure: (transaction: AsynchronousDataTransaction) -> Void) {
AsynchronousDataTransaction( AsynchronousDataTransaction(

View File

@@ -30,26 +30,24 @@ import CoreData
// MARK: - Into // MARK: - Into
/** /**
A `Into` clause contains the destination entity and destination persistent store for a `create(...)` method. A common usage is to just indicate the entity: An `Into` clause contains the destination entity and destination persistent store for a `create(...)` method. A common usage is to just indicate the entity:
```
let person = transaction.create(Into(MyPersonEntity)) let person = transaction.create(Into(MyPersonEntity))
```
For cases where multiple `NSPersistentStore`s contain the same entity, the destination configuration's name needs to be specified as well: For cases where multiple `NSPersistentStore`s contain the same entity, the destination configuration's name needs to be specified as well:
```
let person = transaction.create(Into<MyPersonEntity>("Configuration1")) let person = transaction.create(Into<MyPersonEntity>("Configuration1"))
```
This helps the `NSManagedObjectContext` to determine which */
*/
public struct Into<T: NSManagedObject> { public struct Into<T: NSManagedObject> {
// MARK: Public
/** /**
Initializes an `Into` clause. Initializes an `Into` clause.
Sample Usage: Sample Usage:
```
let person = transaction.create(Into<MyPersonEntity>()) let person = transaction.create(Into<MyPersonEntity>())
*/ ```
*/
public init(){ public init(){
self.configuration = nil self.configuration = nil
@@ -58,13 +56,13 @@ public struct Into<T: NSManagedObject> {
} }
/** /**
Initializes an `Into` clause with the specified entity type. Initializes an `Into` clause with the specified entity type.
Sample Usage: Sample Usage:
```
let person = transaction.create(Into(MyPersonEntity)) let person = transaction.create(Into(MyPersonEntity))
```
- parameter entity: the `NSManagedObject` type to be created - parameter entity: the `NSManagedObject` type to be created
*/ */
public init(_ entity: T.Type) { public init(_ entity: T.Type) {
self.configuration = nil self.configuration = nil
@@ -73,10 +71,13 @@ public struct Into<T: NSManagedObject> {
} }
/** /**
Initializes an `Into` clause with the specified entity class. Initializes an `Into` clause with the specified entity class.
Sample Usage:
- parameter entityClass: the `NSManagedObject` class type to be created ```
*/ let person = transaction.create(Into(MyPersonEntity))
```
- parameter entityClass: the `NSManagedObject` class type to be created
*/
public init(_ entityClass: AnyClass) { public init(_ entityClass: AnyClass) {
self.configuration = nil self.configuration = nil
@@ -85,13 +86,13 @@ public struct Into<T: NSManagedObject> {
} }
/** /**
Initializes an `Into` clause with the specified configuration. Initializes an `Into` clause with the specified configuration.
Sample Usage: Sample Usage:
```
let person = transaction.create(Into<MyPersonEntity>("Configuration1")) let person = transaction.create(Into<MyPersonEntity>("Configuration1"))
```
- parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration. - parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration.
*/ */
public init(_ configuration: String?) { public init(_ configuration: String?) {
self.configuration = configuration self.configuration = configuration
@@ -100,14 +101,14 @@ public struct Into<T: NSManagedObject> {
} }
/** /**
Initializes an `Into` clause with the specified entity type and configuration. Initializes an `Into` clause with the specified entity type and configuration.
Sample Usage: Sample Usage:
```
let person = transaction.create(Into(MyPersonEntity.self, "Configuration1")) let person = transaction.create(Into(MyPersonEntity.self, "Configuration1"))
```
- parameter entity: the `NSManagedObject` type to be created - parameter entity: the `NSManagedObject` type to be created
- parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration. - parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration.
*/ */
public init(_ entity: T.Type, _ configuration: String?) { public init(_ entity: T.Type, _ configuration: String?) {
self.configuration = configuration self.configuration = configuration
@@ -116,14 +117,14 @@ public struct Into<T: NSManagedObject> {
} }
/** /**
Initializes an `Into` clause with the specified entity class and configuration. Initializes an `Into` clause with the specified entity class and configuration.
Sample Usage: Sample Usage:
```
let person = transaction.create(Into(MyPersonEntity.self, "Configuration1")) let person = transaction.create(Into(MyPersonEntity.self, "Configuration1"))
```
- parameter entityClass: the `NSManagedObject` class type to be created - parameter entityClass: the `NSManagedObject` class type to be created
- parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration. - parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s entity type. Set to `nil` to use the default configuration.
*/ */
public init(_ entityClass: AnyClass, _ configuration: String?) { public init(_ entityClass: AnyClass, _ configuration: String?) {
self.configuration = configuration self.configuration = configuration

View File

@@ -26,12 +26,11 @@
import Foundation import Foundation
import CoreData import CoreData
// MARK: - NSManagedObject // MARK: - NSManagedObject
public extension NSManagedObject { public extension NSManagedObject {
// MARK: Public
/** /**
Returns this object's parent `UnsafeDataTransaction` instance if it was created from one. Returns `nil` if the parent transaction is either an `AsynchronousDataTransaction` or a `SynchronousDataTransaction`, or if the object is not managed by CoreStore. Returns this object's parent `UnsafeDataTransaction` instance if it was created from one. Returns `nil` if the parent transaction is either an `AsynchronousDataTransaction` or a `SynchronousDataTransaction`, or if the object is not managed by CoreStore.

View File

@@ -29,46 +29,44 @@ import Foundation
// MARK: - SaveResult // MARK: - SaveResult
/** /**
The `SaveResult` indicates the result of a `commit(...)` for a transaction. The `SaveResult` indicates the result of a `commit(...)` for a transaction.
The `SaveResult` can be treated as a boolean: The `SaveResult` can be treated as a boolean:
```
CoreStore.beginAsynchronous { transaction in CoreStore.beginAsynchronous { transaction in
// ... // ...
let result = transaction.commit() let result = transaction.commit()
if result { if result {
// succeeded // succeeded
} }
else { else {
// failed // failed
} }
} }
```
or as an `enum`, where the resulting associated object can also be inspected: or as an `enum`, where the resulting associated object can also be inspected:
```
CoreStore.beginAsynchronous { transaction in CoreStore.beginAsynchronous { transaction in
// ... // ...
let result = transaction.commit() let result = transaction.commit()
switch result { switch result {
case .Success(let hasChanges): case .Success(let hasChanges):
// hasChanges indicates if there were changes or not // hasChanges indicates if there were changes or not
case .Failure(let error): case .Failure(let error):
// error is the NSError instance for the failure // error is the NSError instance for the failure
} }
} }
``` ```
*/ */
public enum SaveResult { public enum SaveResult {
// MARK: Public
/** /**
`SaveResult.Success` indicates that the `commit()` for the transaction succeeded, either because the save succeeded or because there were no changes to save. The associated value `hasChanges` indicates if there were saved changes or not. `SaveResult.Success` indicates that the `commit()` for the transaction succeeded, either because the save succeeded or because there were no changes to save. The associated value `hasChanges` indicates if there were saved changes or not.
*/ */
case Success(hasChanges: Bool) case Success(hasChanges: Bool)
/** /**
`SaveResult.Failure` indicates that the `commit()` for the transaction failed. The associated object for this value is the related `NSError` instance. `SaveResult.Failure` indicates that the `commit()` for the transaction failed. The associated object for this value is the related `NSError` instance.
*/ */
case Failure(NSError) case Failure(NSError)
@@ -103,6 +101,7 @@ extension SaveResult: BooleanType {
public var boolValue: Bool { public var boolValue: Bool {
switch self { switch self {
case .Success: return true case .Success: return true
case .Failure: return false case .Failure: return false
} }

View File

@@ -33,15 +33,13 @@ import CoreData
// MARK: - SynchronousDataTransaction // MARK: - SynchronousDataTransaction
/** /**
The `SynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginSynchronous(_:)`, or from `CoreStore.beginSynchronous(_:)`. The `SynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginSynchronous(_:)`, or from `CoreStore.beginSynchronous(_:)`.
*/ */
public final class SynchronousDataTransaction: BaseDataTransaction { public final class SynchronousDataTransaction: BaseDataTransaction {
// MARK: Public
/** /**
Saves the transaction changes and waits for completion synchronously. This method should not be used after the `commit()` method was already called once. Saves the transaction changes and waits for completion synchronously. This method should not be used after the `commit()` method was already called once.
*/ */
public func commit() { public func commit() {
CoreStore.assert( CoreStore.assert(
@@ -58,11 +56,11 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Begins a child transaction synchronously where `NSManagedObject` creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once. Begins a child transaction synchronously where `NSManagedObject` creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`. - parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously - returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/ */
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? { public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert( CoreStore.assert(
@@ -84,11 +82,11 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
// MARK: BaseDataTransaction // MARK: BaseDataTransaction
/** /**
Creates a new `NSManagedObject` with the specified entity type. Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration - 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. - 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( CoreStore.assert(
@@ -100,11 +98,11 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once. Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be edited - parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @warn_unused_result
public override func edit<T: NSManagedObject>(object: T?) -> T? { public override func edit<T: NSManagedObject>(object: T?) -> T? {
@@ -117,12 +115,12 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once. Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once.
- parameter into: an `Into` clause specifying the entity type - parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited - parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`. - returns: an editable proxy for the specified `NSManagedObject`.
*/ */
@warn_unused_result @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? {
@@ -135,10 +133,10 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once. Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be deleted - parameter object: the `NSManagedObject` type to be deleted
*/ */
public override func delete(object: NSManagedObject?) { public override func delete(object: NSManagedObject?) {
CoreStore.assert( CoreStore.assert(
@@ -150,12 +148,12 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` to be deleted - parameter object1: the `NSManagedObject` to be deleted
- parameter object2: another `NSManagedObject` to be deleted - parameter object2: another `NSManagedObject` to be deleted
- parameter objects: other `NSManagedObject`s to be deleted - parameter objects: other `NSManagedObject`s 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( CoreStore.assert(
@@ -167,10 +165,10 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Deletes the specified `NSManagedObject`s. Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted - parameter objects: the `NSManagedObject`s to be deleted
*/ */
public override func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) { public override func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert( CoreStore.assert(
@@ -182,7 +180,7 @@ public final class SynchronousDataTransaction: BaseDataTransaction {
} }
/** /**
Rolls back the transaction by resetting the `NSManagedObjectContext`. After calling this method, all `NSManagedObjects` fetched within the transaction will become invalid. This method should not be used after the `commit()` method was already called once. Rolls back the transaction by resetting the `NSManagedObjectContext`. After calling this method, all `NSManagedObjects` fetched within the transaction will become invalid. This method should not be used after the `commit()` method was already called once.
*/ */
@available(*, deprecated=1.3.4, message="Resetting the context is inherently unsafe. This method will be removed in the near future. Use `beginUnsafe()` to create transactions with `undo` support.") @available(*, deprecated=1.3.4, 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() { public func rollback() {

View File

@@ -37,17 +37,15 @@ public typealias DetachedDataTransaction = UnsafeDataTransaction
// MARK: - UnsafeDataTransaction // MARK: - UnsafeDataTransaction
/** /**
The `UnsafeDataTransaction` provides an interface for non-contiguous `NSManagedObject` creates, updates, and deletes. This is useful for making temporary changes, such as partially filled forms. An unsafe transaction object should typically be only used from the main queue. The `UnsafeDataTransaction` provides an interface for non-contiguous `NSManagedObject` creates, updates, and deletes. This is useful for making temporary changes, such as partially filled forms. An unsafe transaction object should typically be only used from the main queue.
*/ */
public final class UnsafeDataTransaction: BaseDataTransaction { public final class UnsafeDataTransaction: BaseDataTransaction {
// MARK: Public
/** /**
Saves the transaction changes asynchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread. Saves the transaction changes asynchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread.
- parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block.
*/ */
public func commit(completion: (result: SaveResult) -> Void) { public func commit(completion: (result: SaveResult) -> Void) {
self.context.saveAsynchronouslyWithCompletion { (result) -> Void in self.context.saveAsynchronouslyWithCompletion { (result) -> Void in

View File

@@ -35,48 +35,48 @@ import CoreData
public extension CoreStore { public extension CoreStore {
/** /**
Returns the `defaultStack`'s model version. The version string is the same as the name of the version-specific .xcdatamodeld file. Returns the `defaultStack`'s model version. The version string is the same as the name of the version-specific .xcdatamodeld file.
*/ */
public static var modelVersion: String { public static var modelVersion: String {
return self.defaultStack.modelVersion return self.defaultStack.modelVersion
} }
/** /**
Returns the entity name-to-class type mapping from the `defaultStack`'s model. Returns the entity name-to-class type mapping from the `defaultStack`'s model.
*/ */
public static var entityTypesByName: [String: NSManagedObject.Type] { public static var entityTypesByName: [String: NSManagedObject.Type] {
return self.defaultStack.entityTypesByName return self.defaultStack.entityTypesByName
} }
/** /**
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from `defaultStack`'s model. 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) return self.defaultStack.entityDescriptionForType(type)
} }
/** /**
Adds an in-memory store to the `defaultStack`. Adds an in-memory store to the `defaultStack`.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`.
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public static func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore { public static func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore {
return try self.defaultStack.addInMemoryStoreAndWait(configuration: configuration) return try self.defaultStack.addInMemoryStoreAndWait(configuration: configuration)
} }
/** /**
Adds to the `defaultStack` an SQLite store from the given SQLite file name. Adds to the `defaultStack` an SQLite store from the given SQLite file name.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to nil. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to nil.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public static func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore { public static func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
return try self.defaultStack.addSQLiteStoreAndWait( return try self.defaultStack.addSQLiteStoreAndWait(
@@ -87,13 +87,13 @@ public extension CoreStore {
} }
/** /**
Adds to the `defaultStack` an SQLite store from the given SQLite file URL. Adds to the `defaultStack` an SQLite store from the given SQLite file URL.
- parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). - parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to nil. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to nil.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public static func addSQLiteStoreAndWait(fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore { public static func addSQLiteStoreAndWait(fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
return try self.defaultStack.addSQLiteStoreAndWait( return try self.defaultStack.addSQLiteStoreAndWait(

View File

@@ -46,19 +46,17 @@ internal let defaultSQLiteStoreURL = defaultDirectory.URLByAppendingPathComponen
// MARK: - DataStack // MARK: - DataStack
/** /**
The `DataStack` encapsulates the data model for the Core Data stack. Each `DataStack` can have multiple data stores, usually specified as a "Configuration" in the model editor. Behind the scenes, the DataStack manages its own `NSPersistentStoreCoordinator`, a root `NSManagedObjectContext` for disk saves, and a shared `NSManagedObjectContext` designed as a read-only model interface for `NSManagedObjects`. The `DataStack` encapsulates the data model for the Core Data stack. Each `DataStack` can have multiple data stores, usually specified as a "Configuration" in the model editor. Behind the scenes, the DataStack manages its own `NSPersistentStoreCoordinator`, a root `NSManagedObjectContext` for disk saves, and a shared `NSManagedObjectContext` designed as a read-only model interface for `NSManagedObjects`.
*/ */
public final class DataStack { public final class DataStack {
// MARK: Public
/** /**
Initializes a `DataStack` from an `NSManagedObjectModel`. Initializes a `DataStack` from an `NSManagedObjectModel`.
- parameter modelName: the name of the (.xcdatamodeld) model file. If not specified, the application name will be used. - parameter modelName: the name of the (.xcdatamodeld) model file. If not specified, the application name will be used.
- parameter bundle: an optional bundle to load models from. If not specified, the main bundle will be used. - 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 incremental migration. If not specified, will default to a non-migrating data stack. - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for incremental migration. If not specified, will default to a non-migrating data stack.
*/ */
public required init(modelName: String = applicationName, bundle: NSBundle = NSBundle.mainBundle(), migrationChain: MigrationChain = nil) { public required init(modelName: String = applicationName, bundle: NSBundle = NSBundle.mainBundle(), migrationChain: MigrationChain = nil) {
CoreStore.assert( CoreStore.assert(
@@ -82,26 +80,26 @@ public final class DataStack {
} }
/** /**
Returns the `DataStack`'s model version. The version string is the same as the name of the version-specific .xcdatamodeld file. Returns the `DataStack`'s model version. The version string is the same as the name of the version-specific .xcdatamodeld file.
*/ */
public var modelVersion: String { public var modelVersion: String {
return self.model.currentModelVersion! return self.model.currentModelVersion!
} }
/** /**
Returns the entity name-to-class type mapping from the `DataStack`'s model. Returns the entity name-to-class type mapping from the `DataStack`'s model.
*/ */
public var entityTypesByName: [String: NSManagedObject.Type] { public var entityTypesByName: [String: NSManagedObject.Type] {
return self.model.entityTypesMapping() return self.model.entityTypesMapping()
} }
/** /**
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass. 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( return NSEntityDescription.entityForName(
self.model.entityNameForClass(type), self.model.entityNameForClass(type),
inManagedObjectContext: self.mainContext inManagedObjectContext: self.mainContext
@@ -109,19 +107,19 @@ public final class DataStack {
} }
/** /**
Returns the `NSManagedObjectID` for the specified object URI if it exists in the persistent store. 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: NSURL) -> NSManagedObjectID? {
return self.coordinator.managedObjectIDForURIRepresentation(url) return self.coordinator.managedObjectIDForURIRepresentation(url)
} }
/** /**
Adds an in-memory store to the stack. Adds an in-memory store to the stack.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`.
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore { public func addInMemoryStoreAndWait(configuration configuration: String? = nil) throws -> NSPersistentStore {
let coordinator = self.coordinator; let coordinator = self.coordinator;
@@ -160,13 +158,13 @@ public final class DataStack {
} }
/** /**
Adds to the stack an SQLite store from the given SQLite file name. Adds to the stack an SQLite store from the given SQLite file name.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore { public func addSQLiteStoreAndWait(fileName fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
return try self.addSQLiteStoreAndWait( return try self.addSQLiteStoreAndWait(
@@ -180,13 +178,13 @@ public final class DataStack {
} }
/** /**
Adds to the stack an SQLite store from the given SQLite file URL. Adds to the stack an SQLite store from the given SQLite file URL.
- parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them. - parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false. - parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to throw exceptions on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- returns: the `NSPersistentStore` added to the stack. - returns: the `NSPersistentStore` added to the stack.
*/ */
public func addSQLiteStoreAndWait(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore { public func addSQLiteStoreAndWait(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) throws -> NSPersistentStore {
CoreStore.assert( CoreStore.assert(

View File

@@ -30,42 +30,40 @@ import CoreData
// MARK: - PersistentStoreResult // MARK: - PersistentStoreResult
/** /**
The `PersistentStoreResult` indicates the result of an asynchronous initialization of a persistent store. The `PersistentStoreResult` indicates the result of an asynchronous initialization of a persistent store.
The `PersistentStoreResult` can be treated as a boolean: The `PersistentStoreResult` can be treated as a boolean:
```
try! CoreStore.addSQLiteStore(completion: { (result: PersistentStoreResult) -> Void in try! CoreStore.addSQLiteStore(completion: { (result: PersistentStoreResult) -> Void in
if result { if result {
// succeeded // succeeded
} }
else { else {
// failed // failed
} }
}) })
```
or as an `enum`, where the resulting associated object can also be inspected: or as an `enum`, where the resulting associated object can also be inspected:
```
try! CoreStore.addSQLiteStore(completion: { (result: PersistentStoreResult) -> Void in try! CoreStore.addSQLiteStore(completion: { (result: PersistentStoreResult) -> Void in
switch result { switch result {
case .Success(let persistentStore): case .Success(let persistentStore):
// persistentStore is the related NSPersistentStore instance // persistentStore is the related NSPersistentStore instance
case .Failure(let error): case .Failure(let error):
// error is the NSError instance for the failure // error is the NSError instance for the failure
} }
}) })
``` ```
*/ */
public enum PersistentStoreResult { public enum PersistentStoreResult {
// MARK: Public
/** /**
`PersistentStoreResult.Success` indicates that the persistent store process succeeded. The associated object for this `enum` value is the related `NSPersistentStore` instance. `PersistentStoreResult.Success` indicates that the persistent store process succeeded. The associated object for this `enum` value is the related `NSPersistentStore` instance.
*/ */
case Success(NSPersistentStore) case Success(NSPersistentStore)
/** /**
`PersistentStoreResult.Failure` indicates that the persistent store process failed. The associated object for this value is the related `NSError` instance. `PersistentStoreResult.Failure` indicates that the persistent store process failed. The associated object for this value is the related `NSError` instance.
*/ */
case Failure(NSError) case Failure(NSError)
@@ -88,9 +86,7 @@ public enum PersistentStoreResult {
internal init(_ errorCode: CoreStoreErrorCode, userInfo: [NSObject: AnyObject]?) { internal init(_ errorCode: CoreStoreErrorCode, userInfo: [NSObject: AnyObject]?) {
self.init(NSError( self.init(NSError(coreStoreErrorCode: errorCode, userInfo: userInfo))
coreStoreErrorCode: errorCode,
userInfo: userInfo))
} }
} }
@@ -99,8 +95,6 @@ public enum PersistentStoreResult {
extension PersistentStoreResult: BooleanType { extension PersistentStoreResult: BooleanType {
// MARK: Public
public var boolValue: Bool { public var boolValue: Bool {
switch self { switch self {