Skip to content

Instantly share code, notes, and snippets.

@sjgroomi
Created July 10, 2015 09:45
Show Gist options
  • Select an option

  • Save sjgroomi/5a3ab2142d9afdf5d1ca to your computer and use it in GitHub Desktop.

Select an option

Save sjgroomi/5a3ab2142d9afdf5d1ca to your computer and use it in GitHub Desktop.
An asynchronous Swift 2.0 Core Data stack loosely based on Marcus Zarra's (http://martiancraft.com/blog/2015/03/core-data-stack/) with asynchronous configuration
//
// SGAsyncSetupCoreDataStore.swift
// Core Data Example
//
// Created by Groom, Stephen on 10/07/2015.
// Copyright © 2015 Stephen Groom. All rights reserved.
//
import CoreData
public enum Fallible<T> {
case Success(T)
case Failure(ErrorType)
}
public enum SGCoreDataError: ErrorType {
case InvalidModelURL
}
public class SGAsyncSetupCoreDataStore {
/**
Used internally so that saving to disk is done asynchronously
*/
private var privateContext: NSManagedObjectContext!
/**
For reading on the main thread only
*/
public var mainContext: NSManagedObjectContext!
/**
For all write operations and fetches which can be performed asynchronously
*/
public var backgroundContext: NSManagedObjectContext!
/**
Attempts to create a core data store in the background and calls a completion when done
:param: modelURL The URL of the .mom or .momd file
:param: storeURL The url used to create or read the SQLite store
:param: completion The completion closure is called with either a fully configured instance of the store
or an ErrorType
:warning: The closure is called on an arbitrary queue
*/
class func setupDataStore(modelURL modelURL: NSURL, storeURL: NSURL, completion: (Fallible<SGAsyncSetupCoreDataStore>) -> ())
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
do {
let instance = SGAsyncSetupCoreDataStore()
guard let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL) else { throw SGCoreDataError.InvalidModelURL }
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType,
configuration: nil,
URL: storeURL,
options: [NSInferMappingModelAutomaticallyOption : true, NSMigratePersistentStoresAutomaticallyOption : true])
instance.privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
instance.privateContext.persistentStoreCoordinator = persistentStoreCoordinator
instance.mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
instance.mainContext.parentContext = instance.privateContext
instance.backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
instance.backgroundContext.parentContext = instance.mainContext
completion(Fallible.Success(instance))
} catch let error {
completion(Fallible.Failure(error))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment