refactor logging functions

This commit is contained in:
John Rommel Estropia
2015-02-28 11:32:41 +09:00
parent 59cd505dc6
commit 55dee6ec2f
11 changed files with 151 additions and 118 deletions

View File

@@ -94,7 +94,7 @@ public class DataStack {
public func addInMemoryStore(configuration: String? = nil) -> PersistentStoreResult {
let coordinator = self.coordinator;
var persistentStoreError: NSError?
var error: NSError?
var store: NSPersistentStore?
coordinator.performSynchronously {
@@ -104,7 +104,7 @@ public class DataStack {
configuration: configuration,
URL: nil,
options: nil,
error: &persistentStoreError)
error: &error)
}
if let store = store {
@@ -112,20 +112,20 @@ public class DataStack {
return PersistentStoreResult(store)
}
if let error = persistentStoreError {
if let error = error {
HardcoreData.handleError(
error,
"Failed to add in-memory NSPersistentStore.")
"Failed to add in-memory \(NSPersistentStore.self).")
return PersistentStoreResult(error)
}
else {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to add in-memory NSPersistentStore.")
"Failed to add in-memory \(NSPersistentStore.self).")
return PersistentStoreResult(.UnknownError)
}
return PersistentStoreResult(.UnknownError)
}
/**
@@ -174,7 +174,8 @@ public class DataStack {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .DifferentPersistentStoreExistsAtURL),
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\" because a different NSPersistentStore at that URL already exists.")
"Failed to add SQLite \(NSPersistentStore.self) at \"\(fileURL)\" because a different \(NSPersistentStore.self) at that URL already exists.")
return PersistentStoreResult(.DifferentPersistentStoreExistsAtURL)
}
@@ -187,7 +188,7 @@ public class DataStack {
error: &directoryError) {
HardcoreData.handleError(
directoryError!,
directoryError ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to create directory for SQLite store at \"\(fileURL)\".")
return PersistentStoreResult(directoryError!)
}
@@ -211,54 +212,45 @@ public class DataStack {
return PersistentStoreResult(store)
}
if let error = persistentStoreError {
if resetStoreOnMigrationFailure
&& (error.code == NSPersistentStoreIncompatibleVersionHashError
|| error.code == NSMigrationMissingSourceModelError)
&& error.domain == NSCocoaErrorDomain {
if let error = persistentStoreError
where (
resetStoreOnMigrationFailure
&& (error.code == NSPersistentStoreIncompatibleVersionHashError
|| error.code == NSMigrationMissingSourceModelError)
&& error.domain == NSCocoaErrorDomain
) {
fileManager.removeItemAtURL(fileURL, error: nil)
fileManager.removeItemAtPath(
fileURL.path!.stringByAppendingString("-shm"),
error: nil)
fileManager.removeItemAtPath(
fileURL.path!.stringByAppendingString("-wal"),
error: nil)
var store: NSPersistentStore?
coordinator.performSynchronously {
fileManager.removeItemAtURL(fileURL, error: nil)
fileManager.removeItemAtPath(
fileURL.path!.stringByAppendingString("-shm"),
error: nil)
fileManager.removeItemAtPath(
fileURL.path!.stringByAppendingString("-wal"),
error: nil)
store = coordinator.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: configuration,
URL: fileURL,
options: [NSSQLitePragmasOption: ["WAL": "journal_mode"],
NSInferMappingModelAutomaticallyOption: true,
NSMigratePersistentStoresAutomaticallyOption: automigrating],
error: &persistentStoreError)
}
if let store = store {
var store: NSPersistentStore?
coordinator.performSynchronously {
store = coordinator.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: configuration,
URL: fileURL,
options: [NSSQLitePragmasOption: ["WAL": "journal_mode"],
NSInferMappingModelAutomaticallyOption: true,
NSMigratePersistentStoresAutomaticallyOption: automigrating],
error: &persistentStoreError)
}
if let store = store {
return PersistentStoreResult(store)
}
}
return PersistentStoreResult(store)
}
}
if let error = persistentStoreError {
HardcoreData.handleError(
error,
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
return PersistentStoreResult(error)
}
else {
HardcoreData.handleError(
NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to add SQLite NSPersistentStore at \"\(fileURL)\".")
}
HardcoreData.handleError(
persistentStoreError ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to add SQLite \(NSPersistentStore.self) at \"\(fileURL)\".")
return PersistentStoreResult(.UnknownError)
}

View File

@@ -46,7 +46,7 @@ public /*abstract*/ class DataTransaction {
public func create<T: NSManagedObject>(entity: T.Type) -> T {
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext() == true, "Attempted to create an entity of type \(entity) outside a transaction queue.")
HardcoreData.assert(!self.isCommitted, "Attempted to create an NSManagedObject from an already committed \(self.dynamicType).")
HardcoreData.assert(!self.isCommitted, "Attempted to create an entity of type \(entity) from an already committed \(self.dynamicType).")
return T.createInContext(self.context)
}

View File

@@ -0,0 +1,75 @@
//
// HardcoreData+Logging.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
// MARK: - HardcoreData
public extension HardcoreData {
// MARK: Public
/**
The HardcoreDataLogger instance to be used. The default logger is an instance of a DefaultLogger.
*/
public static var logger: HardcoreDataLogger = DefaultLogger()
// MARK: Internal
internal static func log(level: LogLevel, message: String, fileName: StaticString = __FILE__, lineNumber: Int = __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: Int = __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: Int = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.assert(
condition,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
}
}

View File

@@ -70,48 +70,6 @@ public enum HardcoreData {
}
/**
The HardcoreDataLogger instance to be used. The default logger is an instance of a DefaultLogger.
*/
public static var logger: HardcoreDataLogger = DefaultLogger()
// MARK: Internal
internal static func log(level: LogLevel, message: String, fileName: StaticString = __FILE__, lineNumber: Int = __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: Int = __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: Int = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.assert(
condition,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName)
}
// MARK: Private
private static let defaultStackBarrierQueue = GCDQueue.createConcurrent("com.hardcoreData.defaultStackBarrierQueue")

View File

@@ -59,25 +59,25 @@ internal extension NSManagedObject {
let objectID = self.objectID
if objectID.temporaryID {
var permanentIDError: NSError?
if !context.obtainPermanentIDsForObjects([self], error: &permanentIDError) {
var error: NSError?
if !context.obtainPermanentIDsForObjects([self], error: &error) {
HardcoreData.handleError(
permanentIDError!,
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to obtain permanent ID for object.")
return nil
}
}
var existingObjectError: NSError?
if let existingObject = context.existingObjectWithID(objectID, error: &existingObjectError) {
var error: NSError?
if let existingObject = context.existingObjectWithID(objectID, error: &error) {
return (existingObject as! T)
}
HardcoreData.handleError(
existingObjectError!,
"Failed to load existing NSManagedObject in context.")
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to load existing \(T.self) in context.")
return nil;
}
}

View File

@@ -75,23 +75,21 @@ internal extension NSManagedObjectContext {
let context = note.object as! NSManagedObjectContext
let insertedObjects = context.insertedObjects
if insertedObjects.count <= 0 {
let numberOfInsertedObjects = insertedObjects.count
if numberOfInsertedObjects <= 0 {
return
}
var permanentIDError: NSError?
if context.obtainPermanentIDsForObjects(Array(insertedObjects), error: &permanentIDError) {
var error: NSError?
if context.obtainPermanentIDsForObjects(Array(insertedObjects), error: &error) {
return
}
if let error = permanentIDError {
HardcoreData.handleError(
error,
"Failed to obtain permanent IDs for inserted objects.")
}
HardcoreData.handleError(
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to obtain permanent ID(s) for \(numberOfInsertedObjects) inserted object(s).")
})
}

View File

@@ -58,7 +58,9 @@ public extension NSManagedObjectContext {
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
HardcoreData.handleError(
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed executing fetch request.")
return nil
}
@@ -90,7 +92,9 @@ public extension NSManagedObjectContext {
}
if fetchResults == nil {
HardcoreData.handleError(error!, "Failed executing fetch request.")
HardcoreData.handleError(
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed executing fetch request.")
return nil
}
@@ -120,7 +124,9 @@ public extension NSManagedObjectContext {
}
if count == NSNotFound {
HardcoreData.handleError(error!, "Failed executing fetch request.")
HardcoreData.handleError(
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed executing fetch request.")
return 0
}

View File

@@ -94,7 +94,7 @@ internal extension NSManagedObjectContext {
HardcoreData.handleError(
error,
"Failed to save NSManagedObjectContext.")
"Failed to save \(NSManagedObjectContext.self).")
result = SaveResult(error)
}
else {
@@ -153,7 +153,7 @@ internal extension NSManagedObjectContext {
HardcoreData.handleError(
error,
"Failed to save NSManagedObjectContext.")
"Failed to save \(NSManagedObjectContext.self).")
if let completion = completion {
GCDQueue.Main.async {

View File

@@ -100,7 +100,7 @@ public struct SortedBy: FetchClause {
if fetchRequest.sortDescriptors != nil {
HardcoreData.log(.Warning, message: "Existing sortDescriptors for the NSFetchRequest was overwritten by SortedBy query clause.")
HardcoreData.log(.Warning, message: "Existing sortDescriptors for the \(NSFetchRequest.self) was overwritten by \(self.dynamicType) query clause.")
}
fetchRequest.sortDescriptors = self.sortDescriptors

View File

@@ -89,7 +89,7 @@ public struct Where: FetchClause {
if fetchRequest.predicate != nil {
HardcoreData.log(.Warning, message: "An existing predicate for the NSFetchRequest was overwritten by Where query clause.")
HardcoreData.log(.Warning, message: "An existing predicate for the \(NSFetchRequest.self) was overwritten by \(self.dynamicType) query clause.")
}
fetchRequest.predicate = self.predicate