Skip to content

Commit

Permalink
Resultを使用するように変更
Browse files Browse the repository at this point in the history
  • Loading branch information
masakih committed Jun 28, 2018
1 parent 6ad9500 commit 2e30bd7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 33 deletions.
22 changes: 7 additions & 15 deletions Doutaku/CoreDataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -209,23 +209,15 @@ public extension CoreDataAccessor {
req.sortDescriptors = sortDescriptors?.sortDescriptors
req.predicate = predicate?.predicate

var result: [T]?
var caughtError: Error?
sync {
do {

result = try self.context.fetch(req)
} catch {

caughtError = error
}
}
if let error = caughtError {

let result: Result<[T]> = sync { Result({ try self.context.fetch(req) }) }

switch result {

throw error
case let .value(r): return r

case let .error(error): throw error
}

return result ?? []
}

func object<T>(of entity: Entity<T>, forURIRepresentation uri: URL) -> T? {
Expand Down
41 changes: 23 additions & 18 deletions Doutaku/MOCGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ final class MOCGenerator {
return model
}

private func isMigrationError(_ code: Int) -> Bool {
private func isMigrationError(_ error: NSError) -> Bool {

if error.domain != NSCocoaErrorDomain { return false }

return [
NSPersistentStoreIncompatibleVersionHashError,
NSMigrationError,
Expand All @@ -82,7 +85,7 @@ final class MOCGenerator {
NSMigrationManagerSourceStoreError,
NSMigrationManagerDestinationStoreError,
NSEntityMigrationPolicyError
].contains(code)
].contains(error.code)
}

private func createCoordinator(_ model: NSManagedObjectModel) throws -> NSPersistentStoreCoordinator {
Expand All @@ -92,30 +95,32 @@ final class MOCGenerator {
throw InnerError.saveLocationIsUnuseable
}

do {
let r = Result({ try makeCoordinator(model) }).recover { result in

return try makeCoordinator(model)

} catch let error as NSError {

// Data Modelが更新されていたらストアファイルを削除してもう一度
if config.tryRemakeStoreFile,
error.domain == NSCocoaErrorDomain,
isMigrationError(error.code) {
switch result {

removeDataFile()
case .value: return result

do {

return try makeCoordinator(model)
case let .error(error as NSError):

// Data Modelが更新されていたらストアファイルを削除してもう一度
if config.tryRemakeStoreFile, isMigrationError(error) {

} catch {
removeDataFile()

print("Fail to create NSPersistentStoreCoordinator twice.")
return Result({ try makeCoordinator(model) })
}

return result
}
}

switch r {

case let .value(result): return result

case let .error(error): throw InnerError.couldNotCreateCoordinator(error.localizedDescription)

throw InnerError.couldNotCreateCoordinator(error.localizedDescription)
}
}

Expand Down

0 comments on commit 2e30bd7

Please sign in to comment.