mirror of
https://github.com/JohnEstropia/CoreStore.git
synced 2026-03-19 07:54:26 +01:00
testing some ways to make querying as elegant as possible
This commit is contained in:
@@ -30,7 +30,7 @@ import GCDKit
|
||||
|
||||
private let applicationSupportDirectory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first as NSURL
|
||||
|
||||
private let applicationName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as String
|
||||
private let applicationName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String ?? "CoreData"
|
||||
|
||||
|
||||
/**
|
||||
@@ -45,7 +45,7 @@ public class DataStack: NSObject {
|
||||
*/
|
||||
public convenience override init() {
|
||||
|
||||
self.init(managedObjectModel: NSManagedObjectModel.mergedModelFromBundles(nil)!)
|
||||
self.init(managedObjectModel: NSManagedObjectModel.mergedModelFromBundles(NSBundle.allBundles())!)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,10 +207,10 @@ public class DataStack: NSObject {
|
||||
|
||||
fileManager.removeItemAtURL(fileURL, error: nil)
|
||||
fileManager.removeItemAtPath(
|
||||
fileURL.absoluteString!.stringByAppendingString("-shm"),
|
||||
fileURL.path!.stringByAppendingString("-shm"),
|
||||
error: nil)
|
||||
fileManager.removeItemAtPath(
|
||||
fileURL.absoluteString!.stringByAppendingString("-wal"),
|
||||
fileURL.path!.stringByAppendingString("-wal"),
|
||||
error: nil)
|
||||
|
||||
var store: NSPersistentStore?
|
||||
@@ -256,11 +256,10 @@ public class DataStack: NSObject {
|
||||
*/
|
||||
public func performTransaction(closure: (transaction: DataTransaction) -> ()) {
|
||||
|
||||
let transaction = DataTransaction(
|
||||
DataTransaction(
|
||||
mainContext: self.mainContext,
|
||||
queue: self.transactionQueue,
|
||||
closure: closure)
|
||||
transaction.perform()
|
||||
closure: closure).perform()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -271,11 +270,10 @@ public class DataStack: NSObject {
|
||||
*/
|
||||
public func performTransactionAndWait(closure: (transaction: DataTransaction) -> ()) -> SaveResult {
|
||||
|
||||
let transaction = DataTransaction(
|
||||
return DataTransaction(
|
||||
mainContext: self.mainContext,
|
||||
queue: self.transactionQueue,
|
||||
closure: closure)
|
||||
return transaction.performAndWait()
|
||||
closure: closure).performAndWait()
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
@@ -50,7 +50,7 @@ public class DataTransaction {
|
||||
public func create<T: NSManagedObject>(entity: T.Type) -> T {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to create an NSManagedObject outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isTransactionCommited, "Attempted to create an NSManagedObject from an already commited DataTransaction.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to create an NSManagedObject from an already committed DataTransaction.")
|
||||
return T.createInContext(self.context)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ public class DataTransaction {
|
||||
public func update<T: NSManagedObject>(object: T) -> T? {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to update an NSManagedObject outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isTransactionCommited, "Attempted to update an NSManagedObject from an already commited DataTransaction.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to update an NSManagedObject from an already committed DataTransaction.")
|
||||
return object.inContext(self.context)
|
||||
}
|
||||
|
||||
@@ -75,12 +75,22 @@ public class DataTransaction {
|
||||
public func delete(object: NSManagedObject) {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to delete an NSManagedObject outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isTransactionCommited, "Attempted to delete an NSManagedObject from an already commited DataTransaction.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to delete an NSManagedObject from an already committed DataTransaction.")
|
||||
object.deleteFromContext()
|
||||
}
|
||||
|
||||
// MARK: Saving changes
|
||||
|
||||
/**
|
||||
Rolls back the transaction by resetting the NSManagedObjectContext. Note that after calling this method, all NSManagedObjects fetched within the transaction will become invalid.
|
||||
*/
|
||||
public func rollback() {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to rollback a DataTransaction outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to rollback an already committed DataTransaction.")
|
||||
self.context.reset()
|
||||
}
|
||||
|
||||
/**
|
||||
Saves the transaction changes asynchronously. Note that this method should not be used after either the commit(_:) or commitAndWait() method was already called once.
|
||||
|
||||
@@ -89,9 +99,9 @@ public class DataTransaction {
|
||||
public func commit(completion: (result: SaveResult) -> ()) {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to commit a DataTransaction outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isTransactionCommited, "Attempted to commit a DataTransaction more than once.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to commit a DataTransaction more than once.")
|
||||
|
||||
self.isTransactionCommited = true
|
||||
self.isCommitted = true
|
||||
self.context.saveAsynchronouslyWithCompletion { [weak self] (result) -> () in
|
||||
|
||||
self?.result = result
|
||||
@@ -107,9 +117,9 @@ public class DataTransaction {
|
||||
public func commitAndWait() -> SaveResult {
|
||||
|
||||
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to commit a DataTransaction outside a transaction queue.")
|
||||
HardcoreData.assert(!self.isTransactionCommited, "Attempted to commit a DataTransaction more than once.")
|
||||
HardcoreData.assert(!self.isCommitted, "Attempted to commit a DataTransaction more than once.")
|
||||
|
||||
self.isTransactionCommited = true
|
||||
self.isCommitted = true
|
||||
let result = self.context.saveSynchronously()
|
||||
self.result = result
|
||||
return result
|
||||
@@ -131,7 +141,7 @@ public class DataTransaction {
|
||||
self.transactionQueue.barrierAsync {
|
||||
|
||||
self.closure(transaction: self)
|
||||
if !self.isTransactionCommited {
|
||||
if !self.isCommitted {
|
||||
|
||||
self.commit { (result) -> () in }
|
||||
}
|
||||
@@ -143,7 +153,7 @@ public class DataTransaction {
|
||||
self.transactionQueue.barrierSync {
|
||||
|
||||
self.closure(transaction: self)
|
||||
if !self.isTransactionCommited {
|
||||
if !self.isCommitted {
|
||||
|
||||
self.commitAndWait()
|
||||
}
|
||||
@@ -154,9 +164,45 @@ public class DataTransaction {
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private var isTransactionCommited = false
|
||||
private var isCommitted = false
|
||||
private var result: SaveResult?
|
||||
private let mainContext: NSManagedObjectContext
|
||||
private let transactionQueue: GCDQueue
|
||||
private let closure: (transaction: DataTransaction) -> ()
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DataContextProvider
|
||||
|
||||
extension DataTransaction: Queryable {
|
||||
|
||||
public func findFirst<T: NSManagedObject>(entity: T.Type) -> T? {
|
||||
|
||||
return self.context.findFirst(entity)
|
||||
}
|
||||
|
||||
public func findFirst<T: NSManagedObject>(query: Query<T>) -> T? {
|
||||
|
||||
return self.context.findFirst(query)
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(entity: T.Type) -> [T]? {
|
||||
|
||||
return self.context.findAll(entity)
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(query: Query<T>) -> [T]? {
|
||||
|
||||
return self.context.findAll(query)
|
||||
}
|
||||
|
||||
public func count<T: NSManagedObject>(entity: T.Type) -> Int {
|
||||
|
||||
return self.context.count(entity)
|
||||
}
|
||||
|
||||
public func count<T: NSManagedObject>(query: Query<T>) -> Int {
|
||||
|
||||
return self.context.count(query)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@
|
||||
//
|
||||
|
||||
import CoreData
|
||||
import GCDKit
|
||||
|
||||
|
||||
/**
|
||||
HardcoreData - Simple, elegant, and smart Core Data management with Swift
|
||||
@@ -35,34 +37,28 @@ public struct HardcoreData {
|
||||
/**
|
||||
The default DataStack instance to be used. If defaultStack is not set before the first time accessed, a default-configured DataStack will be created.
|
||||
|
||||
Note that changing the defaultStack is not thread safe.
|
||||
Changing the defaultStack is thread safe.
|
||||
*/
|
||||
public static var defaultStack = DataStack()
|
||||
|
||||
/**
|
||||
The closure that handles all errors that occur within HardcoreData. The default errorHandler logs errors via the logHandler closure.
|
||||
*/
|
||||
public static var errorHandler = { (error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
|
||||
HardcoreData.logHandler("\(message): \(error)", fileName, lineNumber, functionName)
|
||||
}
|
||||
|
||||
/**
|
||||
The closure that handles all assertions that occur within HardcoreData. The default assertHandler calls assert().
|
||||
*/
|
||||
public static var assertHandler = { (condition: @autoclosure() -> Bool, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
public static var defaultStack: DataStack {
|
||||
|
||||
assert(condition, message, file: fileName, line: lineNumber)
|
||||
}
|
||||
|
||||
/**
|
||||
The closure that handles all logging that occur within HardcoreData. The default logHandler logs via println() when DEBUG is defined; does nothing otherwise.
|
||||
*/
|
||||
public static var logHandler = { (message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
get {
|
||||
|
||||
#if DEBUG
|
||||
println("[\(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n\(message)")
|
||||
#endif
|
||||
self.defaultStackBarrierQueue.barrierSync {
|
||||
|
||||
if self.defaultStackInstance == nil {
|
||||
|
||||
self.defaultStackInstance = DataStack()
|
||||
}
|
||||
}
|
||||
return self.defaultStackInstance!
|
||||
}
|
||||
set {
|
||||
|
||||
self.defaultStackBarrierQueue.barrierAsync {
|
||||
|
||||
self.defaultStackInstance = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,14 +82,100 @@ public struct HardcoreData {
|
||||
return self.defaultStack.performTransactionAndWait(closure)
|
||||
}
|
||||
|
||||
|
||||
public enum LogLevel {
|
||||
|
||||
case Trace
|
||||
case Notice
|
||||
case Alert
|
||||
case Fatal
|
||||
}
|
||||
|
||||
public typealias LogHandlerType = (level: LogLevel, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> ()
|
||||
|
||||
public typealias ErrorHandlerType = (error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> ()
|
||||
|
||||
public typealias AssertionHandlerType = (condition: @autoclosure() -> Bool, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> ()
|
||||
|
||||
|
||||
/**
|
||||
Sets the closure that handles all logging that occur within HardcoreData. The default logHandler logs via println() only when DEBUG is defined.
|
||||
*/
|
||||
public static func setLogHandler(logHandler: LogHandlerType) {
|
||||
|
||||
self.logHandler = logHandler
|
||||
}
|
||||
|
||||
/**
|
||||
Sets the closure that handles all errors that occur within HardcoreData. The default errorHandler logs via println() only when DEBUG is defined.
|
||||
*/
|
||||
public static func setErrorHandler(errorHandler: ErrorHandlerType) {
|
||||
|
||||
self.errorHandler = errorHandler
|
||||
}
|
||||
|
||||
/**
|
||||
Sets the closure that handles all assertions that occur within HardcoreData. The default assertHandler calls assert().
|
||||
*/
|
||||
public static func setAssertionHandler(assertionHandler: AssertionHandlerType) {
|
||||
|
||||
self.assertionHandler = assertionHandler
|
||||
}
|
||||
|
||||
internal static func log(level: LogLevel, message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
|
||||
|
||||
self.logHandler(
|
||||
level: level,
|
||||
message: message,
|
||||
fileName: fileName,
|
||||
lineNumber: lineNumber,
|
||||
functionName: functionName)
|
||||
}
|
||||
|
||||
internal static func handleError(error: NSError, _ message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
|
||||
|
||||
self.errorHandler(error, message, fileName, lineNumber, functionName)
|
||||
self.errorHandler(
|
||||
error: error,
|
||||
message: message,
|
||||
fileName: fileName,
|
||||
lineNumber: lineNumber,
|
||||
functionName: functionName)
|
||||
}
|
||||
|
||||
internal static func assert(condition: @autoclosure() -> Bool, _ message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
|
||||
|
||||
self.assertHandler(condition, message, fileName, lineNumber, functionName)
|
||||
self.assertionHandler(
|
||||
condition: condition,
|
||||
message: message,
|
||||
fileName: fileName,
|
||||
lineNumber: lineNumber,
|
||||
functionName: functionName)
|
||||
}
|
||||
|
||||
|
||||
private static let defaultStackBarrierQueue = GCDQueue.createConcurrent("com.hardcoredata.defaultstackbarrierqueue")
|
||||
|
||||
private static var defaultStackInstance: DataStack?
|
||||
|
||||
private static var logHandler: LogHandlerType = { (level: LogLevel, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
|
||||
#if DEBUG
|
||||
println("[HardcoreData] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
|
||||
#endif
|
||||
}
|
||||
|
||||
private static var errorHandler: ErrorHandlerType = { (error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
|
||||
#if DEBUG
|
||||
println("[HardcoreData] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message): \(error)\n")
|
||||
#endif
|
||||
}
|
||||
|
||||
private static var assertionHandler: AssertionHandlerType = { (condition: @autoclosure() -> Bool, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
|
||||
|
||||
#if DEBUG
|
||||
assert(condition, message, file: fileName, line: lineNumber)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,18 +28,67 @@ import CoreData
|
||||
|
||||
public extension NSManagedObject {
|
||||
|
||||
// MARK: - Entity Utilities
|
||||
|
||||
public class var entityName: String {
|
||||
|
||||
return NSStringFromClass(self).componentsSeparatedByString(".").last!
|
||||
}
|
||||
|
||||
public class func createInContext(context: NSManagedObjectContext) -> Self {
|
||||
public func inContext(context: NSManagedObjectContext) -> Self? {
|
||||
|
||||
return self.typedObjectInContext(context)
|
||||
}
|
||||
|
||||
public func deleteFromContext() {
|
||||
|
||||
self.managedObjectContext?.deleteObject(self)
|
||||
}
|
||||
|
||||
|
||||
// MARK: Querying
|
||||
|
||||
public class func WHERE(predicate: NSPredicate) -> Query<NSManagedObject> {
|
||||
|
||||
return Query(entity: self).WHERE(predicate)
|
||||
}
|
||||
|
||||
public class func WHERE(value: Bool) -> Query<NSManagedObject> {
|
||||
|
||||
return self.WHERE(NSPredicate(value: value))
|
||||
}
|
||||
|
||||
public class func WHERE(format: String, _ args: CVarArgType...) -> Query<NSManagedObject> {
|
||||
|
||||
return self.WHERE(NSPredicate(format: format, arguments: withVaList(args, { $0 })))
|
||||
}
|
||||
|
||||
public class func WHERE(format: String, argumentArray: [AnyObject]?) -> Query<NSManagedObject> {
|
||||
|
||||
return self.WHERE(NSPredicate(format: format, argumentArray: argumentArray))
|
||||
}
|
||||
|
||||
public class func SORTEDBY(order: [SortOrder]) -> Query<NSManagedObject> {
|
||||
|
||||
return Query(entity: self).SORTEDBY(order)
|
||||
}
|
||||
|
||||
public class func SORTEDBY(order: SortOrder, _ subOrder: SortOrder...) -> Query<NSManagedObject> {
|
||||
|
||||
return self.SORTEDBY([order] + subOrder)
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
internal class func createInContext(context: NSManagedObjectContext) -> Self {
|
||||
|
||||
return self(entity: NSEntityDescription.entityForName(self.entityName, inManagedObjectContext: context)!,
|
||||
insertIntoManagedObjectContext: context)
|
||||
}
|
||||
|
||||
public func inContext<T: NSManagedObject>(context: NSManagedObjectContext) -> T? {
|
||||
private func typedObjectInContext<T: NSManagedObject>(context: NSManagedObjectContext) -> T? {
|
||||
|
||||
let objectID = self.objectID
|
||||
if objectID.temporaryID {
|
||||
@@ -65,9 +114,4 @@ public extension NSManagedObject {
|
||||
"Failed to load existing NSManagedObject in context.")
|
||||
return nil;
|
||||
}
|
||||
|
||||
public func deleteFromContext() {
|
||||
|
||||
self.managedObjectContext?.deleteObject(self)
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,6 @@ import Foundation
|
||||
import CoreData
|
||||
import GCDKit
|
||||
|
||||
private var _HardcoreData_NSManagedObjectContext_shouldCascadeSavesToParent: Void?
|
||||
|
||||
public extension NSManagedObjectContext {
|
||||
|
||||
// MARK: - Public
|
||||
@@ -46,66 +44,6 @@ public extension NSManagedObjectContext {
|
||||
}
|
||||
|
||||
|
||||
// MARK: Querying
|
||||
|
||||
public func findFirst<T: NSManagedObject>(entity: T.Type) -> T? {
|
||||
|
||||
return self.findFirst(T.self, predicate: NSPredicate(value: true))
|
||||
}
|
||||
|
||||
public func findFirst<T: NSManagedObject>(entity: T.Type, predicate: NSPredicate) -> T? {
|
||||
|
||||
let fetchRequest = NSFetchRequest()
|
||||
fetchRequest.entity = NSEntityDescription.entityForName(
|
||||
entity.entityName,
|
||||
inManagedObjectContext: self)
|
||||
fetchRequest.fetchLimit = 1
|
||||
|
||||
var fetchResults: [T]?
|
||||
self.performBlockAndWait {
|
||||
|
||||
var error: NSError?
|
||||
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
|
||||
if fetchResults == nil {
|
||||
|
||||
HardcoreData.handleError(
|
||||
error!,
|
||||
"Failed executing fetch request.")
|
||||
}
|
||||
}
|
||||
|
||||
return fetchResults?.first
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(entity: T.Type) -> [T]? {
|
||||
|
||||
return self.findAll(QueryDescriptor<T>(entity: entity))
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(query: QueryDescriptor<T>) -> [T]? {
|
||||
|
||||
let fetchRequest = NSFetchRequest()
|
||||
fetchRequest.entity = NSEntityDescription.entityForName(
|
||||
query.entityName,
|
||||
inManagedObjectContext: self)
|
||||
|
||||
var fetchResults: [T]?
|
||||
self.performBlockAndWait {
|
||||
|
||||
var error: NSError?
|
||||
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
|
||||
if fetchResults == nil {
|
||||
|
||||
HardcoreData.handleError(
|
||||
error!,
|
||||
"Failed executing fetch request.")
|
||||
}
|
||||
}
|
||||
|
||||
return fetchResults
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
internal func saveSynchronously() -> SaveResult {
|
||||
@@ -248,23 +186,24 @@ public extension NSManagedObjectContext {
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private struct ObserverKeys {
|
||||
private struct PropertyKeys {
|
||||
|
||||
static var willSaveNotification: AnyObject?
|
||||
static var didSaveNotification: AnyObject?
|
||||
static var observerForWillSaveNotification: Void?
|
||||
static var observerForDidSaveNotification: Void?
|
||||
static var shouldCascadeSavesToParent: Void?
|
||||
}
|
||||
|
||||
private var observerForWillSaveNotification: NotificationObserver? {
|
||||
|
||||
get {
|
||||
|
||||
return self.getAssociatedObjectForKey(&ObserverKeys.willSaveNotification)
|
||||
return self.getAssociatedObjectForKey(&PropertyKeys.observerForWillSaveNotification)
|
||||
}
|
||||
set {
|
||||
|
||||
self.setAssociatedRetainedObject(
|
||||
newValue,
|
||||
forKey: &ObserverKeys.willSaveNotification)
|
||||
forKey: &PropertyKeys.observerForWillSaveNotification)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,13 +211,13 @@ public extension NSManagedObjectContext {
|
||||
|
||||
get {
|
||||
|
||||
return self.getAssociatedObjectForKey(&ObserverKeys.didSaveNotification)
|
||||
return self.getAssociatedObjectForKey(&PropertyKeys.observerForDidSaveNotification)
|
||||
}
|
||||
set {
|
||||
|
||||
self.setAssociatedRetainedObject(
|
||||
newValue,
|
||||
forKey: &ObserverKeys.didSaveNotification)
|
||||
forKey: &PropertyKeys.observerForDidSaveNotification)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,19 +225,14 @@ public extension NSManagedObjectContext {
|
||||
|
||||
get {
|
||||
|
||||
if let value = objc_getAssociatedObject(self, &_HardcoreData_NSManagedObjectContext_shouldCascadeSavesToParent) as? NSNumber {
|
||||
|
||||
return value.boolValue
|
||||
}
|
||||
return false
|
||||
let number: NSNumber? = self.getAssociatedObjectForKey(&PropertyKeys.observerForDidSaveNotification)
|
||||
return number?.boolValue ?? false
|
||||
}
|
||||
set {
|
||||
|
||||
objc_setAssociatedObject(
|
||||
self,
|
||||
&_HardcoreData_NSManagedObjectContext_shouldCascadeSavesToParent,
|
||||
newValue,
|
||||
objc_AssociationPolicy(OBJC_ASSOCIATION_ASSIGN))
|
||||
self.setAssociatedCopiedObject(
|
||||
NSNumber(bool: newValue),
|
||||
forKey: &PropertyKeys.shouldCascadeSavesToParent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,4 +269,88 @@ public extension NSManagedObjectContext {
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DataContextProvider
|
||||
|
||||
extension NSManagedObjectContext: Queryable {
|
||||
|
||||
public func findFirst<T: NSManagedObject>(entity: T.Type) -> T? {
|
||||
|
||||
return self.findFirst(Query(entity: entity))
|
||||
}
|
||||
|
||||
public func findFirst<T: NSManagedObject>(query: Query<T>) -> T? {
|
||||
|
||||
var query = query
|
||||
query.fetchLimit = 1
|
||||
let fetchRequest = query.createFetchRequestInContext(self)
|
||||
|
||||
var fetchResults: [T]?
|
||||
self.performBlockAndWait {
|
||||
|
||||
var error: NSError?
|
||||
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
|
||||
if fetchResults == nil {
|
||||
|
||||
HardcoreData.handleError(
|
||||
error!,
|
||||
"Failed executing fetch request.")
|
||||
}
|
||||
}
|
||||
|
||||
return fetchResults?.first
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(entity: T.Type) -> [T]? {
|
||||
|
||||
return self.findAll(Query(entity: entity))
|
||||
}
|
||||
|
||||
public func findAll<T: NSManagedObject>(query: Query<T>) -> [T]? {
|
||||
|
||||
let fetchRequest = query.createFetchRequestInContext(self)
|
||||
|
||||
var fetchResults: [T]?
|
||||
self.performBlockAndWait {
|
||||
|
||||
var error: NSError?
|
||||
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
|
||||
if fetchResults == nil {
|
||||
|
||||
HardcoreData.handleError(
|
||||
error!,
|
||||
"Failed executing fetch request.")
|
||||
}
|
||||
}
|
||||
|
||||
return fetchResults
|
||||
}
|
||||
|
||||
public func count<T: NSManagedObject>(entity: T.Type) -> Int {
|
||||
|
||||
return self.count(Query(entity: entity))
|
||||
}
|
||||
|
||||
public func count<T: NSManagedObject>(query: Query<T>) -> Int {
|
||||
|
||||
let fetchRequest = query.createFetchRequestInContext(self)
|
||||
|
||||
var count = 0
|
||||
var error: NSError?
|
||||
self.performBlockAndWait {
|
||||
|
||||
count = self.countForFetchRequest(fetchRequest, error: &error)
|
||||
}
|
||||
if count == NSNotFound {
|
||||
|
||||
HardcoreData.handleError(
|
||||
error!,
|
||||
"Failed executing fetch request.")
|
||||
return 0
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
}
|
||||
|
||||
123
HardcoreData/Query.swift
Normal file
123
HardcoreData/Query.swift
Normal file
@@ -0,0 +1,123 @@
|
||||
//
|
||||
// Query.swift
|
||||
// HardcoreData
|
||||
//
|
||||
// Copyright (c) 2014 John Rommel Estropia
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import CoreData
|
||||
|
||||
|
||||
public typealias AttributeName = Selector
|
||||
|
||||
public enum SortOrder {
|
||||
|
||||
case Ascending(AttributeName)
|
||||
case Descending(AttributeName)
|
||||
}
|
||||
|
||||
public class Query<T: NSManagedObject> {
|
||||
|
||||
public var entityName: String {
|
||||
|
||||
return self.entity.entityName
|
||||
}
|
||||
|
||||
public func WHERE(predicate: NSPredicate) -> Query<T> {
|
||||
|
||||
if self.predicate != nil {
|
||||
|
||||
}
|
||||
self.predicate = predicate
|
||||
return self
|
||||
}
|
||||
|
||||
public func WHERE(value: Bool) -> Query<T> {
|
||||
|
||||
return self.WHERE(NSPredicate(value: value))
|
||||
}
|
||||
|
||||
public func WHERE(format: String, _ args: CVarArgType...) -> Query<T> {
|
||||
|
||||
return self.WHERE(NSPredicate(format: format, arguments: withVaList(args, { $0 })))
|
||||
}
|
||||
|
||||
public func WHERE(format: String, argumentArray: [AnyObject]?) -> Query<T> {
|
||||
|
||||
return self.WHERE(NSPredicate(format: format, argumentArray: argumentArray))
|
||||
}
|
||||
|
||||
public func SORTEDBY(order: [SortOrder]) -> Query<T> {
|
||||
|
||||
self.sortDescriptors = order.map { sortOrder in
|
||||
|
||||
switch sortOrder {
|
||||
|
||||
case .Ascending(let attributeName):
|
||||
return NSSortDescriptor(
|
||||
key: NSStringFromSelector(attributeName),
|
||||
ascending: true)
|
||||
|
||||
case .Descending(let attributeName):
|
||||
return NSSortDescriptor(
|
||||
key: NSStringFromSelector(attributeName),
|
||||
ascending: false)
|
||||
}
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func SORTEDBY(order: SortOrder, _ subOrder: SortOrder...) -> Query<T> {
|
||||
|
||||
return self.SORTEDBY([order] + subOrder)
|
||||
}
|
||||
|
||||
public func createFetchRequestInContext(context: NSManagedObjectContext) -> NSFetchRequest {
|
||||
|
||||
let fetchRequest = NSFetchRequest()
|
||||
fetchRequest.entity = NSEntityDescription.entityForName(
|
||||
self.entityName,
|
||||
inManagedObjectContext: context)
|
||||
fetchRequest.fetchLimit = self.fetchLimit
|
||||
fetchRequest.fetchOffset = self.fetchOffset
|
||||
fetchRequest.fetchBatchSize = self.fetchBatchSize
|
||||
fetchRequest.predicate = self.predicate
|
||||
|
||||
return fetchRequest
|
||||
}
|
||||
|
||||
// MARK: Internal
|
||||
|
||||
internal init(entity: T.Type) {
|
||||
|
||||
self.entity = entity
|
||||
}
|
||||
|
||||
|
||||
// MARK: Private
|
||||
private let entity: T.Type
|
||||
public var fetchLimit: Int = 0
|
||||
public var fetchOffset: Int = 0
|
||||
public var fetchBatchSize: Int = 0
|
||||
public var predicate: NSPredicate?
|
||||
public var sortDescriptors: [NSSortDescriptor]?
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
//
|
||||
// QueryDescriptor.swift
|
||||
// HardcoreData
|
||||
//
|
||||
// Created by John Rommel Estropia on 14/11/16.
|
||||
// Copyright (c) 2014 John Rommel Estropia. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import CoreData
|
||||
|
||||
public struct QueryDescriptor<T: NSManagedObject> {
|
||||
|
||||
public var entityName: String {
|
||||
|
||||
return self.entity.entityName
|
||||
}
|
||||
|
||||
// MARK: Internal
|
||||
|
||||
internal init(entity: T.Type) {
|
||||
self.entity = entity
|
||||
}
|
||||
|
||||
|
||||
// MARK: Private
|
||||
private let entity: T.Type
|
||||
private var predicate: NSPredicate?
|
||||
private var sortDescriptors: [NSSortDescriptor]?
|
||||
}
|
||||
38
HardcoreData/Queryable.swift
Normal file
38
HardcoreData/Queryable.swift
Normal file
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// Queryable.swift
|
||||
// HardcoreData
|
||||
//
|
||||
// Copyright (c) 2014 John Rommel Estropia
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
public protocol Queryable {
|
||||
|
||||
func findFirst<T: NSManagedObject>(entity: T.Type) -> T?
|
||||
func findFirst<T: NSManagedObject>(query: Query<T>) -> T?
|
||||
|
||||
func findAll<T: NSManagedObject>(entity: T.Type) -> [T]?
|
||||
func findAll<T: NSManagedObject>(query: Query<T>) -> [T]?
|
||||
|
||||
func count<T: NSManagedObject>(entity: T.Type) -> Int
|
||||
func count<T: NSManagedObject>(query: Query<T>) -> Int
|
||||
}
|
||||
Reference in New Issue
Block a user