From 8010daa1615d38a138500724c6e9112bc1718365 Mon Sep 17 00:00:00 2001 From: John Rommel Estropia Date: Sun, 7 Dec 2014 23:57:50 +0900 Subject: [PATCH] custom error handling, logging, and asserting --- .gitmodules | 3 - HardcoreData.xcodeproj/project.pbxproj | 69 +++---------- HardcoreData/DataStack.swift | 22 +++-- HardcoreData/HardcoreData.swift | 40 ++++---- .../NSManagedObject+HardcoreData.swift | 6 +- .../NSManagedObjectContext+HardcoreData.swift | 98 +++++++++++++------ HardcoreData/NSObject+HardcoreData.swift | 49 ++++++++++ HardcoreData/NotificationObserver.swift | 52 ++++++++++ Libraries/JEToolkit | 1 - 9 files changed, 217 insertions(+), 123 deletions(-) create mode 100644 HardcoreData/NSObject+HardcoreData.swift create mode 100644 HardcoreData/NotificationObserver.swift delete mode 160000 Libraries/JEToolkit diff --git a/.gitmodules b/.gitmodules index fa50e0b..0a86d62 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "Libraries/JEToolkit"] - path = Libraries/JEToolkit - url = git@github.com:JohnEstropia/JEToolkit.git [submodule "Libraries/GCDKit"] path = Libraries/GCDKit url = git@github.com:JohnEstropia/GCDKit.git diff --git a/HardcoreData.xcodeproj/project.pbxproj b/HardcoreData.xcodeproj/project.pbxproj index 9c6f822..897dfae 100644 --- a/HardcoreData.xcodeproj/project.pbxproj +++ b/HardcoreData.xcodeproj/project.pbxproj @@ -21,7 +21,8 @@ B5D39A0219FD00C9000E91BB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B5D39A0119FD00C9000E91BB /* Foundation.framework */; }; B5D39A0419FD00DE000E91BB /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B5D39A0319FD00DE000E91BB /* UIKit.framework */; }; B5D8080E1A3471A500A44484 /* GCDKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B5D808021A34715700A44484 /* GCDKit.framework */; }; - B5D8080F1A3471A900A44484 /* JEToolkit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B5D808081A34715700A44484 /* JEToolkit.framework */; }; + B5D808161A34947300A44484 /* NotificationObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5D808151A34947300A44484 /* NotificationObserver.swift */; }; + B5D8081A1A3495BD00A44484 /* NSObject+HardcoreData.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5D808191A3495BD00A44484 /* NSObject+HardcoreData.swift */; }; B5E209E01A0726460089C9D4 /* NSManagedObject+HardcoreData.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E209DF1A0726460089C9D4 /* NSManagedObject+HardcoreData.swift */; }; B5F539901A17A6FC00EC763B /* QueryDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5F5398F1A17A6FC00EC763B /* QueryDescriptor.swift */; }; /* End PBXBuildFile section */ @@ -41,20 +42,6 @@ remoteGlobalIDString = 2FBBCAD619A9FE610070E4AB; remoteInfo = GCDKitTests; }; - B5D808071A34715700A44484 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = B5D8074E1A34715700A44484 /* JEToolkit.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 2F74E6F519DFCC7A00FB0C88; - remoteInfo = JEToolkit; - }; - B5D808091A34715700A44484 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = B5D8074E1A34715700A44484 /* JEToolkit.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 2F74E70019DFCC7A00FB0C88; - remoteInfo = JEToolkitTests; - }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ @@ -76,7 +63,8 @@ B5D39A0119FD00C9000E91BB /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; B5D39A0319FD00DE000E91BB /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; B5D806C51A34715700A44484 /* GCDKit.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = GCDKit.xcodeproj; sourceTree = ""; }; - B5D8074E1A34715700A44484 /* JEToolkit.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = JEToolkit.xcodeproj; sourceTree = ""; }; + B5D808151A34947300A44484 /* NotificationObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NotificationObserver.swift; sourceTree = ""; }; + B5D808191A3495BD00A44484 /* NSObject+HardcoreData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSObject+HardcoreData.swift"; sourceTree = ""; }; B5E209DF1A0726460089C9D4 /* NSManagedObject+HardcoreData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSManagedObject+HardcoreData.swift"; sourceTree = ""; }; B5F3D98419F3EB8E009690A6 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; B5F5398F1A17A6FC00EC763B /* QueryDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryDescriptor.swift; sourceTree = ""; }; @@ -87,7 +75,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B5D8080F1A3471A900A44484 /* JEToolkit.framework in Frameworks */, B5D8080E1A3471A500A44484 /* GCDKit.framework in Frameworks */, B5D39A0419FD00DE000E91BB /* UIKit.framework in Frameworks */, B5D39A0219FD00C9000E91BB /* Foundation.framework in Frameworks */, @@ -139,6 +126,7 @@ B5F5398F1A17A6FC00EC763B /* QueryDescriptor.swift */, B5D1E22919FA9E63003B2874 /* PersistentStoreResult.swift */, B5CFD36D1A0775F000B7885F /* SaveResult.swift */, + B5D808141A34945A00A44484 /* Internal */, 2F03A53319C5C6DA005002A5 /* Supporting Files */, ); path = HardcoreData; @@ -184,7 +172,6 @@ isa = PBXGroup; children = ( B5D806BC1A34715700A44484 /* GCDKit */, - B5D806CD1A34715700A44484 /* JEToolkit */, ); path = Libraries; sourceTree = ""; @@ -206,21 +193,13 @@ name = Products; sourceTree = ""; }; - B5D806CD1A34715700A44484 /* JEToolkit */ = { + B5D808141A34945A00A44484 /* Internal */ = { isa = PBXGroup; children = ( - B5D8074E1A34715700A44484 /* JEToolkit.xcodeproj */, + B5D808151A34947300A44484 /* NotificationObserver.swift */, + B5D808191A3495BD00A44484 /* NSObject+HardcoreData.swift */, ); - path = JEToolkit; - sourceTree = ""; - }; - B5D8074F1A34715700A44484 /* Products */ = { - isa = PBXGroup; - children = ( - B5D808081A34715700A44484 /* JEToolkit.framework */, - B5D8080A1A34715700A44484 /* JEToolkitTests.xctest */, - ); - name = Products; + name = Internal; sourceTree = ""; }; /* End PBXGroup section */ @@ -305,10 +284,6 @@ ProductGroup = B5D806C61A34715700A44484 /* Products */; ProjectRef = B5D806C51A34715700A44484 /* GCDKit.xcodeproj */; }, - { - ProductGroup = B5D8074F1A34715700A44484 /* Products */; - ProjectRef = B5D8074E1A34715700A44484 /* JEToolkit.xcodeproj */; - }, ); projectRoot = ""; targets = ( @@ -333,20 +308,6 @@ remoteRef = B5D808031A34715700A44484 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - B5D808081A34715700A44484 /* JEToolkit.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = JEToolkit.framework; - remoteRef = B5D808071A34715700A44484 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - B5D8080A1A34715700A44484 /* JEToolkitTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = JEToolkitTests.xctest; - remoteRef = B5D808091A34715700A44484 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -378,9 +339,11 @@ B5D1E22C19FA9FBC003B2874 /* NSError+HardcoreData.swift in Sources */, B5CFF23E19FD1D1C00D6DFC4 /* NSManagedObjectContext+HardcoreData.swift in Sources */, 2F291E2719C6D3CF007AF63F /* HardcoreData.swift in Sources */, + B5D8081A1A3495BD00A44484 /* NSObject+HardcoreData.swift in Sources */, B5E209E01A0726460089C9D4 /* NSManagedObject+HardcoreData.swift in Sources */, B5D1E22A19FA9E63003B2874 /* PersistentStoreResult.swift in Sources */, B5D399F119FC818E000E91BB /* DataStack.swift in Sources */, + B5D808161A34947300A44484 /* NotificationObserver.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -491,15 +454,12 @@ EMBEDDED_CONTENT_CONTAINS_SWIFT = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - /Users/johnestropia/Documents/XCode, - "Projects/JEToolkit/build/Debug-iphoneos", "$(USER_LIBRARY_DIR)/Developer/Xcode/DerivedData/PhotoSearch-dzwflhandxxuvngptapvysfpcwdx/Build/Products/Debug-iphoneos", - /Users/johnestropia/Documents/XCode, - "Projects/JEToolkit/build/Debug-iphoneos", ); INFOPLIST_FILE = HardcoreData/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + OTHER_SWIFT_FLAGS = "-D DEBUG"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -517,15 +477,12 @@ EMBEDDED_CONTENT_CONTAINS_SWIFT = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - /Users/johnestropia/Documents/XCode, - "Projects/JEToolkit/build/Debug-iphoneos", "$(USER_LIBRARY_DIR)/Developer/Xcode/DerivedData/PhotoSearch-dzwflhandxxuvngptapvysfpcwdx/Build/Products/Debug-iphoneos", - /Users/johnestropia/Documents/XCode, - "Projects/JEToolkit/build/Debug-iphoneos", ); INFOPLIST_FILE = HardcoreData/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + OTHER_SWIFT_FLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; }; diff --git a/HardcoreData/DataStack.swift b/HardcoreData/DataStack.swift index e093f2b..757a58a 100644 --- a/HardcoreData/DataStack.swift +++ b/HardcoreData/DataStack.swift @@ -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) } diff --git a/HardcoreData/HardcoreData.swift b/HardcoreData/HardcoreData.swift index 74e8fda..f4afcf4 100644 --- a/HardcoreData/HardcoreData.swift +++ b/HardcoreData/HardcoreData.swift @@ -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) } } diff --git a/HardcoreData/NSManagedObject+HardcoreData.swift b/HardcoreData/NSManagedObject+HardcoreData.swift index 0ea2132..bf39c30 100644 --- a/HardcoreData/NSManagedObject+HardcoreData.swift +++ b/HardcoreData/NSManagedObject+HardcoreData.swift @@ -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; } diff --git a/HardcoreData/NSManagedObjectContext+HardcoreData.swift b/HardcoreData/NSManagedObjectContext+HardcoreData.swift index 27ecfdf..f86851e 100644 --- a/HardcoreData/NSManagedObjectContext+HardcoreData.swift +++ b/HardcoreData/NSManagedObjectContext+HardcoreData.swift @@ -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.") + } + }) } } \ No newline at end of file diff --git a/HardcoreData/NSObject+HardcoreData.swift b/HardcoreData/NSObject+HardcoreData.swift new file mode 100644 index 0000000..d5f436c --- /dev/null +++ b/HardcoreData/NSObject+HardcoreData.swift @@ -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(key: UnsafePointer) -> T? { + + return objc_getAssociatedObject(self, key) as? T + } + + internal func setAssociatedRetainedObject(object: T?, forKey key: UnsafePointer) { + + objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) + } + + internal func setAssociatedCopiedObject(object: T?, forKey key: UnsafePointer) { + + objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_COPY_NONATOMIC)) + } + + internal func setAssociatedAssignedObject(object: T?, forKey key: UnsafePointer) { + + objc_setAssociatedObject(self, key, object, UInt(OBJC_ASSOCIATION_ASSIGN)) + } +} \ No newline at end of file diff --git a/HardcoreData/NotificationObserver.swift b/HardcoreData/NotificationObserver.swift new file mode 100644 index 0000000..1b214a6 --- /dev/null +++ b/HardcoreData/NotificationObserver.swift @@ -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) + } +} diff --git a/Libraries/JEToolkit b/Libraries/JEToolkit deleted file mode 160000 index 5f2a2b3..0000000 --- a/Libraries/JEToolkit +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5f2a2b37753048b1193f17fe047d84be7e8820b1