custom error handling, logging, and asserting

This commit is contained in:
John Rommel Estropia
2014-12-07 23:57:50 +09:00
parent daa5e64ae0
commit 8010daa161
9 changed files with 217 additions and 123 deletions

View File

@@ -27,6 +27,12 @@ import Foundation
import CoreData
import GCDKit
private let applicationSupportDirectory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first as NSURL
private let applicationName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as String
/**
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.
*/
@@ -101,14 +107,14 @@ public class DataStack: NSObject {
HardcoreData.handleError(
error,
message: "Failed to add in-memory NSPersistentStore.")
"Failed to add in-memory NSPersistentStore.")
return PersistentStoreResult(error)
}
else {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .UnknownError),
message: "Failed to add in-memory NSPersistentStore.")
"Failed to add in-memory NSPersistentStore.")
}
return PersistentStoreResult(.UnknownError)
}
@@ -125,7 +131,7 @@ public class DataStack: NSObject {
public func addSQLiteStore(fileName: String, configuration: String? = nil, automigrating: Bool = true, resetStoreOnMigrationFailure: Bool = false) -> PersistentStoreResult {
return self.addSQLiteStore(
fileURL: NSURL.applicationSupportDirectory().URLByAppendingPathComponent(fileName, isDirectory: false),
fileURL: applicationSupportDirectory.URLByAppendingPathComponent(fileName, isDirectory: false),
configuration: configuration,
automigrating: automigrating,
resetStoreOnMigrationFailure: resetStoreOnMigrationFailure)
@@ -140,7 +146,7 @@ public class DataStack: NSObject {
:param: resetStoreOnMigrationFailure Set to true to delete the store on migration failure; 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: a PersistentStoreResult indicating success or failure.
*/
public func addSQLiteStore(fileURL: NSURL = NSURL.applicationSupportDirectory().URLByAppendingPathComponent(NSString.applicationName(), isDirectory: true).URLByAppendingPathExtension("sqlite"), configuration: String? = nil, automigrating: Bool = true, resetStoreOnMigrationFailure: Bool = false) -> PersistentStoreResult {
public func addSQLiteStore(fileURL: NSURL = applicationSupportDirectory.URLByAppendingPathComponent(applicationName, isDirectory: true).URLByAppendingPathExtension("sqlite"), configuration: String? = nil, automigrating: Bool = true, resetStoreOnMigrationFailure: Bool = false) -> PersistentStoreResult {
let coordinator = self.coordinator;
if let store = coordinator.persistentStoreForURL(fileURL) {
@@ -155,7 +161,7 @@ public class DataStack: NSObject {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .DifferentPersistentStoreExistsAtURL),
message: "Failed to add SQLite NSPersistentStore at \"\(fileURL)\" because a different NSPersistentStore at that URL already exists.")
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\" because a different NSPersistentStore at that URL already exists.")
return PersistentStoreResult(.DifferentPersistentStoreExistsAtURL)
}
@@ -169,7 +175,7 @@ public class DataStack: NSObject {
HardcoreData.handleError(
directoryError!,
message: "Failed to create directory for SQLite store at \"\(fileURL)\".")
"Failed to create directory for SQLite store at \"\(fileURL)\".")
return PersistentStoreResult(directoryError!)
}
@@ -231,14 +237,14 @@ public class DataStack: NSObject {
HardcoreData.handleError(
error,
message: "Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
return PersistentStoreResult(error)
}
else {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .UnknownError),
message: "Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
}
return PersistentStoreResult(.UnknownError)
}

View File

@@ -24,7 +24,6 @@
//
import CoreData
import JEToolkit
/**
HardcoreData - Simple, elegant, and smart Core Data management with Swift
@@ -41,30 +40,29 @@ public struct HardcoreData {
public static var defaultStack = DataStack()
/**
The closure that handles all errors that occur within HardcoreData. The default errorHandler logs errors via JEDumpAlert().
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: String, lineNumber: UWord, functionName: StaticString) -> () in
public static var errorHandler = { (error: NSError, message: String, fileName: StaticString, lineNumber: UWord, functionName: StaticString) -> () in
JEDumpAlert(
error,
message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
HardcoreData.logHandler("\(message): \(error)", fileName, lineNumber, functionName)
}
public static var assertHandler = { (condition: @autoclosure() -> Bool, message: String, fileName: String, lineNumber: UWord, functionName: StaticString) -> () in
/**
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
JEAssert(
condition,
message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
assert(condition, message, file: fileName, line: lineNumber)
}
public static var logHandler = { (message: String, fileName: String, lineNumber: Int32, functionName: String) -> () in
/**
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
#if DEBUG
println("[\(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))] \(fileName.stringValue.lastPathComponent):\(lineNumber) \(functionName)\n\(message)")
#endif
}
/**
@@ -88,14 +86,14 @@ public struct HardcoreData {
return self.defaultStack.performTransactionAndWait(closure)
}
internal static func handleError(error: NSError, _ message: String, fileName: String = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
internal static func handleError(error: NSError, _ message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
self.errorHandler(error, message, fileName.lastPathComponent, lineNumber, functionName)
self.errorHandler(error, message, fileName, lineNumber, functionName)
}
internal static func assert(condition: @autoclosure() -> Bool, _ message: String, fileName: String = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
internal static func assert(condition: @autoclosure() -> Bool, _ message: String, fileName: StaticString = __FILE__, lineNumber: UWord = __LINE__, functionName: StaticString = __FUNCTION__) {
self.assertHandler(condition, message, fileName.lastPathComponent, lineNumber, functionName)
self.assertHandler(condition, message, fileName, lineNumber, functionName)
}
}

View File

@@ -30,7 +30,7 @@ public extension NSManagedObject {
public class var entityName: String {
return self.className().componentsSeparatedByString(".").last!
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
public class func createInContext(context: NSManagedObjectContext) -> Self {
@@ -49,7 +49,7 @@ public extension NSManagedObject {
HardcoreData.handleError(
permanentIDError!,
message: "Failed to obtain permanent ID for object.")
"Failed to obtain permanent ID for object.")
return nil
}
}
@@ -62,7 +62,7 @@ public extension NSManagedObject {
HardcoreData.handleError(
existingObjectError!,
message: "Failed to load existing NSManagedObject in context.")
"Failed to load existing NSManagedObject in context.")
return nil;
}

View File

@@ -70,7 +70,7 @@ public extension NSManagedObjectContext {
HardcoreData.handleError(
error!,
message: "Failed executing fetch request.")
"Failed executing fetch request.")
}
}
@@ -98,7 +98,7 @@ public extension NSManagedObjectContext {
HardcoreData.handleError(
error!,
message: "Failed executing fetch request.")
"Failed executing fetch request.")
}
}
@@ -144,7 +144,7 @@ public extension NSManagedObjectContext {
HardcoreData.handleError(
error,
message: "Failed to save NSManagedObjectContext.")
"Failed to save NSManagedObjectContext.")
result = SaveResult(error)
}
else {
@@ -198,7 +198,7 @@ public extension NSManagedObjectContext {
HardcoreData.handleError(
error,
message: "Failed to save NSManagedObjectContext.")
"Failed to save NSManagedObjectContext.")
if let completion = completion {
GCDBlock.async(.Main) {
@@ -233,14 +233,14 @@ public extension NSManagedObjectContext {
context.parentContext = rootContext
context.setupForHardcoreDataWithContextName("com.hardcoredata.maincontext")
context.shouldCascadeSavesToParent = true
context.registerForNotificationsWithName(
NSManagedObjectContextDidSaveNotification,
fromObject: rootContext,
targetQueue: NSOperationQueue.mainQueue()) {
[unowned context] (note) -> () in
context.observerForDidSaveNotification = NotificationObserver(
notificationName: NSManagedObjectContextDidSaveNotification,
object: rootContext,
closure: { [weak context] (note) -> () in
context.mergeChangesFromContextDidSaveNotification(note)
}
context?.mergeChangesFromContextDidSaveNotification(note)
return
})
return context
}
@@ -248,6 +248,40 @@ public extension NSManagedObjectContext {
// MARK: - Private
private struct ObserverKeys {
static var willSaveNotification: AnyObject?
static var didSaveNotification: AnyObject?
}
private var observerForWillSaveNotification: NotificationObserver? {
get {
return self.getAssociatedObjectForKey(&ObserverKeys.willSaveNotification)
}
set {
self.setAssociatedRetainedObject(
newValue,
forKey: &ObserverKeys.willSaveNotification)
}
}
private var observerForDidSaveNotification: NotificationObserver? {
get {
return self.getAssociatedObjectForKey(&ObserverKeys.didSaveNotification)
}
set {
self.setAssociatedRetainedObject(
newValue,
forKey: &ObserverKeys.didSaveNotification)
}
}
private var shouldCascadeSavesToParent: Bool {
get {
@@ -275,28 +309,30 @@ public extension NSManagedObjectContext {
self.name = contextName
}
self.registerForNotificationsWithName(NSManagedObjectContextWillSaveNotification, fromObject: self) {
(note) -> () in
let context: NSManagedObjectContext = note.object as NSManagedObjectContext
let insertedObjects = context.insertedObjects
if insertedObjects.count <= 0 {
self.observerForWillSaveNotification = NotificationObserver(
notificationName: NSManagedObjectContextWillSaveNotification,
object: self,
closure: { (note) -> () in
return
}
var permanentIDError: NSError?
if context.obtainPermanentIDsForObjects(insertedObjects.allObjects, error: &permanentIDError) {
let context = note.object as NSManagedObjectContext
let insertedObjects = context.insertedObjects
if insertedObjects.count <= 0 {
return
}
return
}
if let error = permanentIDError {
var permanentIDError: NSError?
if context.obtainPermanentIDsForObjects(insertedObjects.allObjects, error: &permanentIDError) {
return
}
HardcoreData.handleError(
error,
message: "Failed to obtain permanent IDs for inserted objects.")
}
}
if let error = permanentIDError {
HardcoreData.handleError(
error,
"Failed to obtain permanent IDs for inserted objects.")
}
})
}
}

View File

@@ -0,0 +1,49 @@
//
// NSObject+HardcoreData.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
internal extension NSObject {
internal func getAssociatedObjectForKey<T: AnyObject>(key: UnsafePointer<Void>) -> T? {
return objc_getAssociatedObject(self, key) as? T
}
internal func setAssociatedRetainedObject<T: AnyObject>(object: T?, forKey key: UnsafePointer<Void>) {
objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
internal func setAssociatedCopiedObject<T: AnyObject>(object: T?, forKey key: UnsafePointer<Void>) {
objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_COPY_NONATOMIC))
}
internal func setAssociatedAssignedObject<T: AnyObject>(object: T?, forKey key: UnsafePointer<Void>) {
objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_ASSIGN))
}
}

View File

@@ -0,0 +1,52 @@
//
// NotificationObserver.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
internal class NotificationObserver {
let notificationName: String
let object: AnyObject?
let observer: NSObjectProtocol
init(notificationName: String, object: AnyObject?, closure: (note: NSNotification!) -> ()) {
self.notificationName = notificationName
self.object = object
self.observer = NSNotificationCenter.defaultCenter().addObserverForName(
notificationName,
object: object,
queue: nil,
usingBlock: closure)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self.observer,
name: self.notificationName,
object: self.object)
}
}