Last active
October 11, 2017 05:28
-
-
Save darcwader/4263bd0e25eabe3d89f24480d8aee098 to your computer and use it in GitHub Desktop.
Core Data Coordinator for iOS 11 Apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| final class DataCoordinator { | |
| //MARK: - singleton | |
| private static var coordinator: DataCoordinator? | |
| public class func sharedInstance() -> DataCoordinator { | |
| if coordinator == nil { | |
| coordinator = DataCoordinator() | |
| } | |
| return coordinator! | |
| } | |
| //MARK: - init | |
| public var container : NSPersistentContainer | |
| private init() { | |
| container = NSPersistentContainer(name: "Model") | |
| container.loadPersistentStores(completionHandler: { (_, error) in | |
| if let error = error { | |
| fatalError("Unresolved error \(error)") | |
| } | |
| }) | |
| } | |
| //MARK: - perform methods | |
| static func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { | |
| DataCoordinator.sharedInstance().container.performBackgroundTask(block) | |
| } | |
| static func performViewTask(_ block: @escaping (NSManagedObjectContext) -> Void) { | |
| block(DataCoordinator.sharedInstance().container.viewContext) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DataCoordinator.performViewTask { (context) in | |
| let eventFR : NSFetchRequest<DataEvent> = DataEvent.fetchRequest() | |
| do { | |
| eventFR.returnsObjectsAsFaults = false | |
| let res = try context.fetch(eventFR) | |
| print(res) | |
| } catch { | |
| print("oops, could not fetch data in main thread") | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DataCoordinator.performBackgroundTask { (context) in | |
| let obj = DataEvent(context: context) | |
| obj.title = "Test 6" | |
| do { | |
| print(context.hasChanges) | |
| try context.save() | |
| print("saved changes") | |
| } catch { | |
| print("exception saving in background thread") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment