diff --git a/CoreDataDemo.xcodeproj/project.pbxproj b/CoreDataDemo.xcodeproj/project.pbxproj index a4f48d2..f4a3149 100644 --- a/CoreDataDemo.xcodeproj/project.pbxproj +++ b/CoreDataDemo.xcodeproj/project.pbxproj @@ -15,6 +15,8 @@ 6D08495D22F77E4E009B09A2 /* AddSpeakerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D08495C22F77E4E009B09A2 /* AddSpeakerViewController.swift */; }; 6D08495F22F77E58009B09A2 /* AddSessionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D08495E22F77E58009B09A2 /* AddSessionViewController.swift */; }; 6D08496122F77EA9009B09A2 /* SessionTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D08496022F77EA9009B09A2 /* SessionTableViewCell.swift */; }; + 7A02983322F788FB00BC0AAC /* Demo.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 7A02983122F788FB00BC0AAC /* Demo.xcdatamodeld */; }; + 7A02985A22F78B9C00BC0AAC /* DataStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A02985922F78B9C00BC0AAC /* DataStore.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -28,6 +30,8 @@ 6D08495C22F77E4E009B09A2 /* AddSpeakerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddSpeakerViewController.swift; sourceTree = ""; }; 6D08495E22F77E58009B09A2 /* AddSessionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddSessionViewController.swift; sourceTree = ""; }; 6D08496022F77EA9009B09A2 /* SessionTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTableViewCell.swift; sourceTree = ""; }; + 7A02983222F788FB00BC0AAC /* Demo.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Demo.xcdatamodel; sourceTree = ""; }; + 7A02985922F78B9C00BC0AAC /* DataStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataStore.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -60,7 +64,9 @@ 6D08494522F777D2009B09A2 /* CoreDataDemo */ = { isa = PBXGroup; children = ( + 7A02983122F788FB00BC0AAC /* Demo.xcdatamodeld */, 6D08494622F777D2009B09A2 /* AppDelegate.swift */, + 7A02985922F78B9C00BC0AAC /* DataStore.swift */, 6D08494C22F777D3009B09A2 /* Main.storyboard */, 6D08494F22F777D3009B09A2 /* Assets.xcassets */, 6D08495122F777D3009B09A2 /* LaunchScreen.storyboard */, @@ -144,6 +150,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 7A02985A22F78B9C00BC0AAC /* DataStore.swift in Sources */, + 7A02983322F788FB00BC0AAC /* Demo.xcdatamodeld in Sources */, 6D08494722F777D2009B09A2 /* AppDelegate.swift in Sources */, 6D08495F22F77E58009B09A2 /* AddSessionViewController.swift in Sources */, 6D08496122F77EA9009B09A2 /* SessionTableViewCell.swift in Sources */, @@ -346,6 +354,19 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCVersionGroup section */ + 7A02983122F788FB00BC0AAC /* Demo.xcdatamodeld */ = { + isa = XCVersionGroup; + children = ( + 7A02983222F788FB00BC0AAC /* Demo.xcdatamodel */, + ); + currentVersion = 7A02983222F788FB00BC0AAC /* Demo.xcdatamodel */; + path = Demo.xcdatamodeld; + sourceTree = ""; + versionGroupType = wrapper.xcdatamodel; + }; +/* End XCVersionGroup section */ }; rootObject = 6D08493B22F777D2009B09A2 /* Project object */; } diff --git a/CoreDataDemo/AddSessionViewController.swift b/CoreDataDemo/AddSessionViewController.swift index fd752bb..b1e9704 100644 --- a/CoreDataDemo/AddSessionViewController.swift +++ b/CoreDataDemo/AddSessionViewController.swift @@ -7,6 +7,7 @@ // import UIKit +import CoreData class AddSessionViewController: UIViewController { @@ -22,6 +23,39 @@ class AddSessionViewController: UIViewController { formatter.dateStyle = .long return formatter }() + + private var selectedSpeakerIndex: Int? + private var selectedDate: Date? { + didSet { + guard let date = selectedDate else { return } + dateField.text = dateFormatter.string(from: date) + } + } + + private lazy var fetchedResultsController: NSFetchedResultsController = { + let fetchRequest: NSFetchRequest = Speaker.fetchRequest() + + let sortDescriptor = NSSortDescriptor(keyPath: \Speaker.name, ascending: true) + + fetchRequest.sortDescriptors = [sortDescriptor] + + let fetchedResultsController = NSFetchedResultsController( + fetchRequest: fetchRequest, + managedObjectContext: DataStore.shared.managedObjectContext, + sectionNameKeyPath: nil, // not using sections + cacheName: nil // no need for caching + ) + + do { + try fetchedResultsController.performFetch() + } catch { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + let nserror = error as NSError + fatalError("Error fetching speakers: \(nserror), \(nserror.userInfo)") + } + return fetchedResultsController + }() override func viewDidLoad() { super.viewDidLoad() @@ -31,6 +65,8 @@ class AddSessionViewController: UIViewController { speakerField.inputView = speakerPicker dateField.inputView = datePicker + datePicker.addTarget(self, action: #selector(datePicked(_:)), for: .primaryActionTriggered) + datePicker.datePickerMode = .date } @IBAction func cancelTapped() { @@ -38,14 +74,32 @@ class AddSessionViewController: UIViewController { } @IBAction func addTapped(_ sender: Any) { - guard let title = titleField.text, !title.isEmpty else { - let alert = UIAlertController(title: "Title can’t be empty", message: nil, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) - present(alert, animated: true, completion: nil) - return + guard let title = titleField.text, !title.isEmpty, + let speakerIndex = selectedSpeakerIndex, + let speaker = fetchedResultsController.fetchedObjects?[speakerIndex], + let date = selectedDate else { + let alert = UIAlertController(title: "All Fields Required", message: nil, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) + present(alert, animated: true, completion: nil) + return } - // TODO: add session to Core Data + + let session = Session(context: DataStore.shared.managedObjectContext) + session.title = title + session.speaker = speaker + session.date = date dismiss(animated: true, completion: nil) + DataStore.shared.saveContext() + } + +} + +// Actions +extension AddSessionViewController { + + @objc + func datePicked(_ sender: UIDatePicker) { + selectedDate = sender.date } } @@ -56,8 +110,7 @@ extension AddSessionViewController: UIPickerViewDataSource { } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { - // TODO: populate from Core Data - return 1 + return fetchedResultsController.fetchedObjects?.count ?? 0 } } @@ -65,7 +118,12 @@ extension AddSessionViewController: UIPickerViewDataSource { extension AddSessionViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { - return "TODO: speakers from Core Data" + return fetchedResultsController.fetchedObjects?[row].name + } + + func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { + selectedSpeakerIndex = row + speakerField.text = fetchedResultsController.fetchedObjects?[row].name } } diff --git a/CoreDataDemo/AddSpeakerViewController.swift b/CoreDataDemo/AddSpeakerViewController.swift index 891d82f..67fafff 100644 --- a/CoreDataDemo/AddSpeakerViewController.swift +++ b/CoreDataDemo/AddSpeakerViewController.swift @@ -29,7 +29,11 @@ class AddSpeakerViewController: UIViewController { present(alert, animated: true, completion: nil) return } - // TODO: add name to Core Data + + let moc = DataStore.shared.managedObjectContext + let speaker = Speaker(context: moc) + speaker.name = name dismiss(animated: true, completion: nil) + DataStore.shared.saveContext() } } diff --git a/CoreDataDemo/AppDelegate.swift b/CoreDataDemo/AppDelegate.swift index 8aadaa3..c4aaf11 100644 --- a/CoreDataDemo/AppDelegate.swift +++ b/CoreDataDemo/AppDelegate.swift @@ -7,40 +7,26 @@ // import UIKit +import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } - func applicationWillResignActive(_ application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. - } - func applicationDidEnterBackground(_ application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - } - - func applicationWillEnterForeground(_ application: UIApplication) { - // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. - } - - func applicationDidBecomeActive(_ application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + // Saves changes in the application's managed object context when the app enters the background. + DataStore.shared.saveContext() } func applicationWillTerminate(_ application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + // Saves changes in the application's managed object context before the application terminates. + DataStore.shared.saveContext() } - } - diff --git a/CoreDataDemo/DataStore.swift b/CoreDataDemo/DataStore.swift new file mode 100644 index 0000000..0a0c848 --- /dev/null +++ b/CoreDataDemo/DataStore.swift @@ -0,0 +1,67 @@ +// +// DataStore.swift +// CoreDataDemo +// +// Created by Zev Eisenberg on 8/4/19. +// Copyright © 2019 Matthew Dias. All rights reserved. +// + +import CoreData + +class DataStore { + + // Note: having a shared/singleton data store isn't great practice, but it + // simplifies a few things for this demo app. It is better to have a data + // store at the top level of your app, such as in your App Delegate, and + // then pass it down to objectst that need it. Passing the data store around + // makes it much easier to test your classes by passing them a mock data + // store, or a data store that does not save changes to disk. + static var shared = DataStore() + + var managedObjectContext: NSManagedObjectContext { + return persistentContainer.viewContext + } + + private init() { } + + private lazy var persistentContainer: NSPersistentContainer = { + /* + The persistent container for the application. This implementation + creates and returns a container, having loaded the store for the + application to it. + */ + let container = NSPersistentContainer(name: "Demo") + container.loadPersistentStores(completionHandler: { (storeDescription, error) in + if let error = error as NSError? { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + + /* + Typical reasons for an error here include: + * The parent directory does not exist, cannot be created, or disallows writing. + * The persistent store is not accessible, due to permissions or data protection when the device is locked. + * The device is out of space. + * The store could not be migrated to the current model version. + Check the error message to determine what the actual problem was. + */ + fatalError("Unresolved error \(error), \(error.userInfo)") + } + }) + return container + }() + + func saveContext () { + let context = persistentContainer.viewContext + if context.hasChanges { + do { + try context.save() + } catch { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + let nserror = error as NSError + fatalError("Unresolved error \(nserror), \(nserror.userInfo)") + } + } + } + +} diff --git a/CoreDataDemo/Demo.xcdatamodeld/Demo.xcdatamodel/contents b/CoreDataDemo/Demo.xcdatamodeld/Demo.xcdatamodel/contents new file mode 100644 index 0000000..937a264 --- /dev/null +++ b/CoreDataDemo/Demo.xcdatamodeld/Demo.xcdatamodel/contents @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CoreDataDemo/SessionsViewController.swift b/CoreDataDemo/SessionsViewController.swift index bb2afb7..49ce208 100644 --- a/CoreDataDemo/SessionsViewController.swift +++ b/CoreDataDemo/SessionsViewController.swift @@ -7,6 +7,7 @@ // import UIKit +import CoreData class SessionsViewController: UITableViewController { @@ -21,25 +22,57 @@ class SessionsViewController: UITableViewController { } - // MARK: - Table view data source + private lazy var fetchedResultsController: NSFetchedResultsController = { + let fetchRequest: NSFetchRequest = Session.fetchRequest() + + let sortDescriptor = NSSortDescriptor(keyPath: \Session.date, ascending: true) + + fetchRequest.sortDescriptors = [sortDescriptor] + + let fetchedResultsController = NSFetchedResultsController( + fetchRequest: fetchRequest, + managedObjectContext: DataStore.shared.managedObjectContext, + sectionNameKeyPath: nil, // not using sections + cacheName: nil // no need for caching + ) + fetchedResultsController.delegate = self + + do { + try fetchedResultsController.performFetch() + } catch { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + let nserror = error as NSError + fatalError("Error fetching speakers: \(nserror), \(nserror.userInfo)") + } + return fetchedResultsController + }() - override func numberOfSections(in tableView: UITableView) -> Int { - // #warning Incomplete implementation, return the number of sections - return 0 - } + + // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - // #warning Incomplete implementation, return the number of rows - return 0 + return fetchedResultsController.fetchedObjects?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "sessionCell", for: indexPath) as! SessionTableViewCell + let session = fetchedResultsController.fetchedObjects?[indexPath.row] - // Configure the cell... + cell.titleLabel.text = session?.title + cell.speakerLabel.text = session?.speaker?.name.map { "by \($0)" } + cell.dateLabel.text = session?.date.map(dateFormatter.string(from:)) return cell } } + +extension SessionsViewController: NSFetchedResultsControllerDelegate { + + func controllerDidChangeContent(_ controller: NSFetchedResultsController) { + tableView.reloadData() + } + +}