This commit is contained in:
John Rommel Estropia
2015-02-13 01:37:59 +09:00
parent 6b8bb3e434
commit f78895b812
26 changed files with 1044 additions and 503 deletions

View File

@@ -0,0 +1,51 @@
//
// CustomizeQuery.swift
// HardcoreData
//
// Copyright (c) 2015 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
// MARK: - CustomizeQuery
public struct CustomizeQuery: FetchClause {
// MARK: Public
public init(_ customization: (fetchRequest: NSFetchRequest) -> Void) {
self.customization = customization
}
// MARK: QueryClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
self.customization(fetchRequest: fetchRequest)
}
private let customization: (fetchRequest: NSFetchRequest) -> Void
}

View File

@@ -28,11 +28,13 @@ import CoreData
import GCDKit
private let applicationSupportDirectory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first as NSURL
private let applicationSupportDirectory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first as! NSURL
private let applicationName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String ?? "CoreData"
private let applicationName = ((NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData")
// 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 acting as a model interface for NSManagedObjects.
*/
@@ -283,3 +285,59 @@ public class DataStack: NSObject {
private let mainContext: NSManagedObjectContext
private let transactionQueue: GCDQueue;
}
// MARK: - DataStack+DataContextProvider
//extension DataStack: ObjectQueryable {
//
// public func firstObject<T: NSManagedObject>(entity: T.Type) -> T? {
//
// return self.mainContext.firstObject(entity)
// }
//
// public func firstObject<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> T? {
//
// return self.mainContext.firstObject(entity, customizeFetch: customizeFetch)
// }
//
// public func firstObject<T: NSManagedObject>(query: ObjectQuery<T>) -> T? {
//
// return self.mainContext.firstObject(query)
// }
//
// public func firstObject<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> T? {
//
// return self.mainContext.firstObject(query, customizeFetch: customizeFetch)
// }
//
// public func allObjects<T: NSManagedObject>(entity: T.Type) -> [T]? {
//
// return self.mainContext.allObjects(entity)
// }
//
// public func allObjects<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> [T]? {
//
// return self.mainContext.allObjects(entity, customizeFetch: customizeFetch)
// }
//
// public func allObjects<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]? {
//
// return self.mainContext.allObjects(query)
// }
//
// public func allObjects<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> [T]? {
//
// return self.mainContext.allObjects(query, customizeFetch: customizeFetch)
// }
//
// public func countObjects<T: NSManagedObject>(entity: T.Type) -> Int {
//
// return self.mainContext.countObjects(entity)
// }
//
// public func countObjects<T: NSManagedObject>(query: ObjectQuery<T>) -> Int {
//
// return self.mainContext.countObjects(query)
// }
//}

View File

@@ -0,0 +1,61 @@
//
// DataTransaction+Querying.swift
// HardcoreData
//
// Copyright (c) 2015 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
extension DataTransaction {
public func fetchOne<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> T? {
return self.context.fetchOne(entity, queryClauses)
}
public func fetchOne<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> T? {
return self.context.fetchOne(entity, queryClauses)
}
public func fetchAll<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> [T]? {
return self.context.fetchAll(entity, queryClauses)
}
public func fetchAll<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> [T]? {
return self.context.fetchAll(entity, queryClauses)
}
public func queryCount<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> Int {
return self.context.queryCount(entity, queryClauses)
}
public func queryCount<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> Int {
return self.context.queryCount(entity, queryClauses)
}
}

View File

@@ -27,6 +27,9 @@ import Foundation
import CoreData
import GCDKit
// MARK: - DataTransaction
/**
The DataTransaction 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.performTransaction(_:), or from HardcoreData.performTransaction(_:).
*/
@@ -60,7 +63,7 @@ public final class DataTransaction {
:param: object the NSManagedObject type to be edited
:returns: an editable proxy for the specified NSManagedObject.
*/
public func update<T: NSManagedObject>(object: T) -> T? {
public func fetch<T: NSManagedObject>(object: T) -> T? {
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to update an NSManagedObject outside a transaction queue.")
HardcoreData.assert(!self.isCommitted, "Attempted to update an NSManagedObject from an already committed DataTransaction.")
@@ -132,6 +135,8 @@ public final class DataTransaction {
self.transactionQueue = queue
self.context = mainContext.temporaryContext()
self.closure = closure
self.context.parentTransaction = self
}
internal func perform() {
@@ -160,59 +165,3 @@ public final class DataTransaction {
private let transactionQueue: GCDQueue
private let closure: (transaction: DataTransaction) -> ()
}
// MARK: - DataContextProvider
extension DataTransaction: ObjectQueryable {
public func findFirst<T: NSManagedObject>(entity: T.Type) -> T? {
return self.context.findFirst(entity)
}
public func findFirst<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> T? {
return self.context.findFirst(entity, customizeFetch: customizeFetch)
}
public func findFirst<T: NSManagedObject>(query: ObjectQuery<T>) -> T? {
return self.context.findFirst(query)
}
public func findFirst<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> T? {
return self.context.findFirst(query, customizeFetch: customizeFetch)
}
public func findAll<T: NSManagedObject>(entity: T.Type) -> [T]? {
return self.context.findAll(entity)
}
public func findAll<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> [T]? {
return self.context.findAll(entity, customizeFetch: customizeFetch)
}
public func findAll<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]? {
return self.context.findAll(query)
}
public func findAll<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> [T]? {
return self.context.findAll(query, customizeFetch: customizeFetch)
}
public func count<T: NSManagedObject>(entity: T.Type) -> Int {
return self.context.count(entity)
}
public func count<T: NSManagedObject>(query: ObjectQuery<T>) -> Int {
return self.context.count(query)
}
}

View File

@@ -0,0 +1,51 @@
//
// DefaultLogger.swift
// HardcoreData
//
// Copyright (c) 2015 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
public final class DefaultLogger: HardcoreDataLogger {
public func log(#level: LogLevel, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) {
#if DEBUG
Swift.println("[HardcoreData] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n")
#endif
}
public func handleError(#error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) {
#if DEBUG
Swift.println("[HardcoreData] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message): \(error)\n")
#endif
}
public func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) {
#if DEBUG
Swift.assert(condition, message, file: fileName, line: lineNumber)
#endif
}
}

View File

@@ -1,5 +1,5 @@
//
// ObjectQueryable.swift
// FetchClause.swift
// HardcoreData
//
// Copyright (c) 2014 John Rommel Estropia
@@ -23,25 +23,13 @@
// SOFTWARE.
//
import UIKit
import Foundation
import CoreData
public typealias FetchRequestCustomization = (fetchRequest: NSFetchRequest) -> ()
// MARK: - FetchClause
public protocol ObjectQueryable {
func findFirst<T: NSManagedObject>(entity: T.Type) -> T?
func findFirst<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> T?
func findFirst<T: NSManagedObject>(query: ObjectQuery<T>) -> T?
func findFirst<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> T?
func findAll<T: NSManagedObject>(entity: T.Type) -> [T]?
func findAll<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> [T]?
func findAll<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]?
func findAll<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> [T]?
func count<T: NSManagedObject>(entity: T.Type) -> Int
func count<T: NSManagedObject>(query: ObjectQuery<T>) -> Int
public protocol FetchClause {
func applyToFetchRequest(fetchRequest: NSFetchRequest)
}

View File

@@ -27,6 +27,11 @@ import CoreData
import GCDKit
typealias HCD = HardcoreData
// MARK: HardcoreData
/**
The HardcoreData struct is the main entry point for all other APIs.
*/
@@ -59,6 +64,55 @@ public struct HardcoreData {
}
}
/**
The HardcoreDataLogger instance to be used. The default logger is an instance of a DefaultLogger.
*/
public static var logger: HardcoreDataLogger = DefaultLogger()
internal static func log(level: LogLevel, message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.log(
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.logger.handleError(
error: error,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
}
internal static func assert(@autoclosure condition: () -> Bool, _ message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.assert(
condition,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
}
private static let defaultStackBarrierQueue = GCDQueue.createConcurrent("com.hardcoreData.defaultStackBarrierQueue")
private static var defaultStackInstance: DataStack?
}
extension HardcoreData {
/**
Using the defaultStack, begins a transaction asynchronously where NSManagedObject creates, updates, and deletes can be made.
@@ -79,102 +133,59 @@ public struct HardcoreData {
return self.defaultStack.performTransactionAndWait(closure)
}
public enum LogLevel {
case Trace
case Notice
case Warning
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: 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.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
}
}
//extension HardcoreData {
//
// public static func firstObject<T: NSManagedObject>(entity: T.Type) -> T? {
//
// return self.defaultStack.firstObject(entity)
// }
//
// public static func firstObject<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> T? {
//
// return self.defaultStack.firstObject(entity, customizeFetch: customizeFetch)
// }
//
// public static func firstObject<T: NSManagedObject>(query: ObjectQuery<T>) -> T? {
//
// return self.defaultStack.firstObject(query)
// }
//
// public static func firstObject<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> T? {
//
// return self.defaultStack.firstObject(query, customizeFetch: customizeFetch)
// }
//
// public static func allObjects<T: NSManagedObject>(entity: T.Type) -> [T]? {
//
// return self.defaultStack.allObjects(entity)
// }
//
// public static func allObjects<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> [T]? {
//
// return self.defaultStack.allObjects(entity, customizeFetch: customizeFetch)
// }
//
// public static func allObjects<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]? {
//
// return self.defaultStack.allObjects(query)
// }
//
// public static func allObjects<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> [T]? {
//
// return self.defaultStack.allObjects(query, customizeFetch: customizeFetch)
// }
//
// public static func countObjects<T: NSManagedObject>(entity: T.Type) -> Int {
//
// return self.defaultStack.countObjects(entity)
// }
//
// public static func countObjects<T: NSManagedObject>(query: ObjectQuery<T>) -> Int {
//
// return self.defaultStack.countObjects(query)
// }
//}

View File

@@ -0,0 +1,45 @@
//
// HardcoreDataLogger.swift
// HardcoreData
//
// Copyright (c) 2015 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
public enum LogLevel {
case Trace
case Notice
case Warning
case Fatal
}
public protocol HardcoreDataLogger {
func log(#level: LogLevel, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString)
func handleError(#error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString)
func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString)
}

View File

@@ -46,6 +46,9 @@ public enum HardcoreDataErrorCode: Int {
case DifferentPersistentStoreExistsAtURL
}
// MARK: - NSError+HardcoreData
public extension NSError {
/**
@@ -58,6 +61,9 @@ public extension NSError {
: nil)
}
// MARK: Internal
internal convenience init(hardcoreDataErrorCode: HardcoreDataErrorCode) {
self.init(hardcoreDataErrorCode: hardcoreDataErrorCode, userInfo: nil)

View File

@@ -26,64 +26,19 @@
import Foundation
import CoreData
public extension NSManagedObject {
// MARK: - NSManagedObject+HardcoreData
extension NSManagedObject {
// MARK: - Entity Utilities
public class var entityName: String {
// TODO: map from model file
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
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) -> ObjectQuery<NSManagedObject> {
return ObjectQuery(entity: self).WHERE(predicate)
}
public class func WHERE(value: Bool) -> ObjectQuery<NSManagedObject> {
return self.WHERE(NSPredicate(value: value))
}
public class func WHERE(format: String, _ args: CVarArgType...) -> ObjectQuery<NSManagedObject> {
return self.WHERE(NSPredicate(format: format, arguments: getVaList(args)))
}
public class func WHERE(format: String, argumentArray: [AnyObject]?) -> ObjectQuery<NSManagedObject> {
return self.WHERE(NSPredicate(format: format, argumentArray: argumentArray))
}
public class func WHERE(attributeName: AttributeName, isEqualTo value: NSObject?) -> ObjectQuery<NSManagedObject> {
return ObjectQuery(entity: self).WHERE(attributeName, isEqualTo: value)
}
public class func SORTEDBY(order: [SortOrder]) -> ObjectQuery<NSManagedObject> {
return ObjectQuery(entity: self).SORTEDBY(order)
}
public class func SORTEDBY(order: SortOrder, _ subOrder: SortOrder...) -> ObjectQuery<NSManagedObject> {
return self.SORTEDBY([order] + subOrder)
}
// MARK: - Internal
@@ -93,6 +48,16 @@ public extension NSManagedObject {
insertIntoManagedObjectContext: context)
}
internal func inContext(context: NSManagedObjectContext) -> Self? {
return self.typedObjectInContext(context)
}
internal func deleteFromContext() {
self.managedObjectContext?.deleteObject(self)
}
private func typedObjectInContext<T: NSManagedObject>(context: NSManagedObjectContext) -> T? {
let objectID = self.objectID
@@ -111,7 +76,7 @@ public extension NSManagedObject {
var existingObjectError: NSError?
if let existingObject = context.existingObjectWithID(objectID, error: &existingObjectError) {
return (existingObject as T)
return (existingObject as! T)
}
HardcoreData.handleError(

View File

@@ -27,6 +27,9 @@ import Foundation
import CoreData
import GCDKit
// MARK: - NSManagedObjectContext+HardcoreData
public extension NSManagedObjectContext {
// MARK: - Public
@@ -39,6 +42,8 @@ public extension NSManagedObjectContext {
context.parentContext = self
context.setupForHardcoreDataWithContextName("com.hardcoredata.temporarycontext")
context.shouldCascadeSavesToParent = true
context.parentStack = self.parentStack
context.parentTransaction = self.parentTransaction
return context
}
@@ -46,6 +51,44 @@ public extension NSManagedObjectContext {
// MARK: - Internal
internal var parentStack: DataStack? {
get {
return self.getAssociatedObjectForKey(&PropertyKeys.parentStack)
}
set {
self.setAssociatedAssignedObject(
newValue,
forKey: &PropertyKeys.parentStack)
}
}
internal var parentTransaction: DataTransaction? {
get {
return self.getAssociatedObjectForKey(&PropertyKeys.parentTransaction)
}
set {
self.setAssociatedAssignedObject(
newValue,
forKey: &PropertyKeys.parentTransaction)
}
}
internal func temporaryContextInTransaction(transaction: DataTransaction?) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = self
context.setupForHardcoreDataWithContextName("com.hardcoredata.temporarycontext")
context.shouldCascadeSavesToParent = true
return context
}
internal func saveSynchronously() -> SaveResult {
var result: SaveResult = SaveResult(hasChanges: false)
@@ -109,8 +152,7 @@ public extension NSManagedObjectContext {
return
}
self.performBlock {
[unowned self] () -> () in
self.performBlock { () -> () in
var saveError: NSError?
if self.save(&saveError) {
@@ -191,6 +233,8 @@ public extension NSManagedObjectContext {
static var observerForWillSaveNotification: Void?
static var observerForDidSaveNotification: Void?
static var shouldCascadeSavesToParent: Void?
static var parentStack: Void?
static var parentTransaction: Void?
}
private var observerForWillSaveNotification: NotificationObserver? {
@@ -248,7 +292,7 @@ public extension NSManagedObjectContext {
object: self,
closure: { (note) -> () in
let context = note.object as NSManagedObjectContext
let context = note.object as! NSManagedObjectContext
let insertedObjects = context.insertedObjects
if insertedObjects.count <= 0 {
@@ -256,7 +300,7 @@ public extension NSManagedObjectContext {
}
var permanentIDError: NSError?
if context.obtainPermanentIDsForObjects(insertedObjects.allObjects, error: &permanentIDError) {
if context.obtainPermanentIDsForObjects(Array(insertedObjects), error: &permanentIDError) {
return
}
@@ -271,104 +315,3 @@ public extension NSManagedObjectContext {
}
}
// MARK: - DataContextProvider
extension NSManagedObjectContext: ObjectQueryable {
public func findFirst<T: NSManagedObject>(entity: T.Type) -> T? {
return self.findFirst(entity, customizeFetch: nil)
}
public func findFirst<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> T? {
return self.findFirst(ObjectQuery(entity: entity), customizeFetch: customizeFetch)
}
public func findFirst<T: NSManagedObject>(query: ObjectQuery<T>) -> T? {
return self.findFirst(query, customizeFetch: nil)
}
public func findFirst<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> T? {
let fetchRequest = query.createFetchRequestForContext(self)
customizeFetch?(fetchRequest: fetchRequest)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
var fetchResults: [T]?
var error: NSError?
self.performBlockAndWait {
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
return nil
}
return fetchResults?.first
}
public func findAll<T: NSManagedObject>(entity: T.Type) -> [T]? {
return self.findAll(entity, customizeFetch: nil)
}
public func findAll<T: NSManagedObject>(entity: T.Type, customizeFetch: FetchRequestCustomization?) -> [T]? {
return self.findAll(ObjectQuery(entity: entity), customizeFetch: customizeFetch)
}
public func findAll<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]? {
return self.findAll(query, customizeFetch: nil)
}
public func findAll<T: NSManagedObject>(query: ObjectQuery<T>, customizeFetch: FetchRequestCustomization?) -> [T]? {
let fetchRequest = query.createFetchRequestForContext(self)
fetchRequest.fetchLimit = 0
var fetchResults: [T]?
var error: NSError?
self.performBlockAndWait {
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
return nil
}
return fetchResults
}
public func count<T: NSManagedObject>(entity: T.Type) -> Int {
return self.count(ObjectQuery(entity: entity))
}
public func count<T: NSManagedObject>(query: ObjectQuery<T>) -> Int {
let fetchRequest = query.createFetchRequestForContext(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
}
}

View File

@@ -0,0 +1,157 @@
//
// NSManagedObjectContext+Querying.swift
// HardcoreData
//
// Copyright (c) 2015 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
extension NSManagedObjectContext {
public func fetchOne<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> T? {
return self.fetchOne(entity, queryClauses)
}
public func fetchOne<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> T? {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(
entity.entityName,
inManagedObjectContext: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
for clause in queryClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [T]?
var error: NSError?
self.performBlockAndWait {
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
return nil
}
return fetchResults?.first
}
public func fetchAll<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> [T]? {
return self.fetchAll(entity, queryClauses)
}
public func fetchAll<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> [T]? {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(
entity.entityName,
inManagedObjectContext: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
for clause in queryClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [T]?
var error: NSError?
self.performBlockAndWait {
fetchResults = self.executeFetchRequest(fetchRequest, error: &error) as? [T]
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
return nil
}
return fetchResults
}
public func queryCount<T: NSManagedObject>(entity: T.Type, _ queryClauses: FetchClause...) -> Int {
return self.queryCount(entity, queryClauses)
}
public func queryCount<T: NSManagedObject>(entity: T.Type, _ queryClauses: [FetchClause]) -> Int {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(
entity.entityName,
inManagedObjectContext: self)
for clause in queryClauses {
clause.applyToFetchRequest(fetchRequest)
}
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
}
// public func queryCount<T: NSManagedObject, U: IntegerType>(entity: T.Type, _ queryClauses: [FetchClause]) -> U? {
//
//// let expressionDescription = NSExpressionDescription()
//// expressionDescription.name = "queryCount"
//// expressionDescription.expressionResultType = .Integer32AttributeType
//// expressionDescription.expression = NSExpression(
//// forFunction: "min:",
//// arguments: [NSExpression(forKeyPath: attribute)])
//
// let request = NSFetchRequest(entityName: entity.entityName)
// request.resultType = .DictionaryResultType
// request.predicate = predicate
// request.propertiesToFetch = [expressionDescription]
//
// var error: NSError?
// let results = NSManagedObjectContext.context()?.executeFetchRequest(request, error: &error)
// if results == nil {
//
// JEDumpAlert(error, "error")
// return nil
// }
//
// return (results?.first as? [String: NSDate])?[expressionDescription.name]
// }
}

View File

@@ -25,6 +25,9 @@
import Foundation
// MARK: - NSObject+HardcoreData
internal extension NSObject {
internal func getAssociatedObjectForKey<T: AnyObject>(key: UnsafePointer<Void>) -> T? {

View File

@@ -26,6 +26,9 @@
import Foundation
import CoreData
// MARK: - NSPersistentStoreCoordinator+HardcoreData
public extension NSPersistentStoreCoordinator {
public func performSynchronously(closure: () -> ()) {

View File

@@ -25,6 +25,9 @@
import Foundation
// MARK: - NotificationObserver
internal final class NotificationObserver {
let notificationName: String

View File

@@ -1,134 +0,0 @@
//
// ObjectQuery.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 final class ObjectQuery<T: NSManagedObject> {
public var fetchLimit: Int = 0
public var fetchOffset: Int = 0
public var fetchBatchSize: Int = 0
public var entityName: String {
return self.entity.entityName
}
public func WHERE(predicate: NSPredicate) -> ObjectQuery<T> {
if self.predicate != nil {
HardcoreData.log(.Warning, message: "Attempted to set a Query's WHERE clause more than once. The last predicate set will be used.")
}
self.predicate = predicate
return self
}
public func WHERE(value: Bool) -> ObjectQuery<T> {
return self.WHERE(NSPredicate(value: value))
}
public func WHERE(format: String, _ args: CVarArgType...) -> ObjectQuery<T> {
return self.WHERE(NSPredicate(format: format, arguments: getVaList(args)))
}
public func WHERE(format: String, argumentArray: [AnyObject]?) -> ObjectQuery<T> {
return self.WHERE(NSPredicate(format: format, argumentArray: argumentArray))
}
public func WHERE(attributeName: AttributeName, isEqualTo value: NSObject?) -> ObjectQuery<T> {
return self.WHERE(value == nil
? NSPredicate(format: "\(attributeName) == nil")!
: NSPredicate(format: "\(attributeName) == %@", value!)!)
}
public func SORTEDBY(order: [SortOrder]) -> ObjectQuery<T> {
if self.sortDescriptors != nil {
HardcoreData.log(.Warning, message: "Attempted to set a Query's SORTEDBY clause more than once. The last sort order set will be used.")
}
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...) -> ObjectQuery<T> {
return self.SORTEDBY([order] + subOrder)
}
// MARK: Internal
internal init(entity: T.Type) {
self.entity = entity
}
internal func createFetchRequestForContext(context: NSManagedObjectContext) -> NSFetchRequest {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(
self.entityName,
inManagedObjectContext: context)
fetchRequest.predicate = self.predicate
fetchRequest.sortDescriptors = self.sortDescriptors
return fetchRequest
}
// MARK: Private
private let entity: T.Type
private var predicate: NSPredicate?
private var sortDescriptors: [NSSortDescriptor]?
}

View File

@@ -26,6 +26,9 @@
import Foundation
import CoreData
// MARK: - PersistentStoreResult
public enum PersistentStoreResult {
case Success(NSPersistentStore)
@@ -54,6 +57,9 @@ public enum PersistentStoreResult {
}
}
// MARK: - PersistentStoreResult+BooleanType
extension PersistentStoreResult: BooleanType {
public var boolValue: Bool {

View File

@@ -1,5 +1,5 @@
//
// ValueQueryable.swift
// FetchClause.swift
// HardcoreData
//
// Copyright (c) 2014 John Rommel Estropia
@@ -24,15 +24,12 @@
//
import Foundation
import CoreData
public protocol ValueQueryable {
// MARK: - QueryClause
public protocol QueryClause {
func findFirst<T: NSManagedObject>(entity: T.Type) -> T?
func findFirst<T: NSManagedObject>(query: ObjectQuery<T>) -> T?
func findAll<T: NSManagedObject>(entity: T.Type) -> [T]?
func findAll<T: NSManagedObject>(query: ObjectQuery<T>) -> [T]?
func count<T: NSManagedObject>(entity: T.Type) -> Int
func count<T: NSManagedObject>(query: ObjectQuery<T>) -> Int
func applyToFetchRequest(fetchRequest: NSFetchRequest)
}

View File

@@ -25,6 +25,9 @@
import Foundation
// MARK: - SaveResult
public enum SaveResult {
case Success(hasChanges: Bool)
@@ -53,6 +56,9 @@ public enum SaveResult {
}
}
// MARK: - SaveResult+BooleanType
extension SaveResult: BooleanType {
public var boolValue: Bool {

104
HardcoreData/SortedBy.swift Normal file
View File

@@ -0,0 +1,104 @@
//
// SortedBy.swift
// HardcoreData
//
// Copyright (c) 2015 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
public func +(left: SortedBy, right: SortedBy) -> SortedBy {
return SortedBy(left.sortDescriptors + right.sortDescriptors)
}
public typealias AttributeName = Selector
public enum SortOrder {
case Ascending(AttributeName)
case Descending(AttributeName)
}
// MARK: - SortedBy
public struct SortedBy: FetchClause {
// MARK: Public
public init(_ sortDescriptors: [NSSortDescriptor]) {
self.sortDescriptors = sortDescriptors
}
public init() {
self.init([NSSortDescriptor]())
}
public init(_ sortDescriptor: NSSortDescriptor) {
self.init([sortDescriptor])
}
public init(_ order: [SortOrder]) {
self.init(order.map { sortOrder -> NSSortDescriptor 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)
}
})
}
public init(_ order: SortOrder, _ subOrder: SortOrder...) {
self.init([order] + subOrder)
}
public let sortDescriptors: [NSSortDescriptor]
// MARK: QueryClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.sortDescriptors != nil {
HardcoreData.log(.Warning, message: "Existing sortDescriptors for the NSFetchRequest was overwritten by SortedBy query clause.")
}
fetchRequest.sortDescriptors = self.sortDescriptors
}
}

97
HardcoreData/Where.swift Normal file
View File

@@ -0,0 +1,97 @@
//
// Where.swift
// HardcoreData
//
// Copyright (c) 2015 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
public func &&(left: Where, right: Where) -> Where {
return Where(NSCompoundPredicate(type: .AndPredicateType, subpredicates: [left.predicate, right.predicate]))
}
public func ||(left: Where, right: Where) -> Where {
return Where(NSCompoundPredicate(type: .OrPredicateType, subpredicates: [left.predicate, right.predicate]))
}
public prefix func !(clause: Where) -> Where {
return Where(NSCompoundPredicate(type: .NotPredicateType, subpredicates: [clause.predicate]))
}
// MARK: - Where
public struct Where: FetchClause {
// MARK: Public
public init(_ predicate: NSPredicate) {
self.predicate = predicate
}
public init() {
self.init(true)
}
public init(_ value: Bool) {
self.init(NSPredicate(value: value))
}
public init(_ format: String, _ args: CVarArgType...) {
self.init(NSPredicate(format: format, arguments: getVaList(args)))
}
public init(_ format: String, argumentArray: [AnyObject]?) {
self.init(NSPredicate(format: format, argumentArray: argumentArray))
}
public init(_ attributeName: AttributeName, isEqualTo value: NSObject?) {
self.init(value == nil
? NSPredicate(format: "\(attributeName) == nil")
: NSPredicate(format: "\(attributeName) == %@", value!))
}
public let predicate: NSPredicate
// MARK: QueryClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if fetchRequest.predicate != nil {
HardcoreData.log(.Warning, message: "An existing predicate for the NSFetchRequest was overwritten by Where query clause.")
}
fetchRequest.predicate = self.predicate
}
}