Skip to content

Add core data #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CoreDataDemo.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -28,6 +30,8 @@
6D08495C22F77E4E009B09A2 /* AddSpeakerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddSpeakerViewController.swift; sourceTree = "<group>"; };
6D08495E22F77E58009B09A2 /* AddSessionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddSessionViewController.swift; sourceTree = "<group>"; };
6D08496022F77EA9009B09A2 /* SessionTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTableViewCell.swift; sourceTree = "<group>"; };
7A02983222F788FB00BC0AAC /* Demo.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Demo.xcdatamodel; sourceTree = "<group>"; };
7A02985922F78B9C00BC0AAC /* DataStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataStore.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -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 */,
Expand Down Expand Up @@ -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 */,
Expand Down Expand Up @@ -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 = "<group>";
versionGroupType = wrapper.xcdatamodel;
};
/* End XCVersionGroup section */
};
rootObject = 6D08493B22F777D2009B09A2 /* Project object */;
}
76 changes: 67 additions & 9 deletions CoreDataDemo/AddSessionViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import UIKit
import CoreData

class AddSessionViewController: UIViewController {

Expand All @@ -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<Speaker> = {
let fetchRequest: NSFetchRequest<Speaker> = 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()
Expand All @@ -31,21 +65,41 @@ class AddSessionViewController: UIViewController {
speakerField.inputView = speakerPicker

dateField.inputView = datePicker
datePicker.addTarget(self, action: #selector(datePicked(_:)), for: .primaryActionTriggered)
datePicker.datePickerMode = .date
}

@IBAction func cancelTapped() {
dismiss(animated: true, completion: nil)
}

@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
}

}
Expand All @@ -56,16 +110,20 @@ extension AddSessionViewController: UIPickerViewDataSource {
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// TODO: populate from Core Data
return 1
return fetchedResultsController.fetchedObjects?.count ?? 0
}

}

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
}

}
6 changes: 5 additions & 1 deletion CoreDataDemo/AddSpeakerViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
24 changes: 5 additions & 19 deletions CoreDataDemo/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}


}

67 changes: 67 additions & 0 deletions CoreDataDemo/DataStore.swift
Original file line number Diff line number Diff line change
@@ -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)")
}
}
}

}
16 changes: 16 additions & 0 deletions CoreDataDemo/Demo.xcdatamodeld/Demo.xcdatamodel/contents
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14492.1" systemVersion="18G87" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Session" representedClassName="Session" syncable="YES" codeGenerationType="class">
<attribute name="date" attributeType="Date" usesScalarValueType="NO" syncable="YES"/>
<attribute name="title" attributeType="String" syncable="YES"/>
<relationship name="speaker" maxCount="1" deletionRule="Nullify" destinationEntity="Speaker" inverseName="sessions" inverseEntity="Speaker" syncable="YES"/>
</entity>
<entity name="Speaker" representedClassName="Speaker" syncable="YES" codeGenerationType="class">
<attribute name="name" attributeType="String" syncable="YES"/>
<relationship name="sessions" optional="YES" toMany="YES" deletionRule="Nullify" destinationEntity="Session" inverseName="speaker" inverseEntity="Session" syncable="YES"/>
</entity>
<elements>
<element name="Session" positionX="-54" positionY="0" width="128" height="90"/>
<element name="Speaker" positionX="-315.38671875" positionY="14.421875" width="128" height="75"/>
</elements>
</model>
49 changes: 41 additions & 8 deletions CoreDataDemo/SessionsViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import UIKit
import CoreData

class SessionsViewController: UITableViewController {

Expand All @@ -21,25 +22,57 @@ class SessionsViewController: UITableViewController {

}

// MARK: - Table view data source
private lazy var fetchedResultsController: NSFetchedResultsController<Session> = {
let fetchRequest: NSFetchRequest<Session> = 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<NSFetchRequestResult>) {
tableView.reloadData()
}

}