-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathViewController.swift
194 lines (146 loc) · 5.95 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//
// ViewController.swift
// Notes
//
// Created by Bart Jacobs on 08/03/2017.
// Copyright © 2017 Cocoacasts. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
// MARK: - Properties
@IBOutlet var tableView: UITableView!
// MARK: -
fileprivate let coreDataManager = CoreDataManager(modelName: "Notes")
// MARK: -
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Note> = {
// Initialize Fetch Request
let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest()
// Add Sort Descriptors
let sortDescriptor = NSSortDescriptor(key: "updatedAt", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// Initialize Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataManager.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Save Note")
print("\(fetchError), \(fetchError.localizedDescription)")
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else { return }
switch identifier {
case "SegueAddNoteViewController":
guard let navigationController = segue.destination as? UINavigationController else { return }
guard let viewController = navigationController.viewControllers.first as? AddNoteViewController else { return }
// Configure View Controller
viewController.delegate = self
case "SegueNoteViewController":
guard let indexPath = tableView.indexPathForSelectedRow else { return }
guard let viewController = segue.destination as? NoteViewController else { return }
// Fetch Note
let note = fetchedResultsController.object(at: indexPath)
// Configure View Controller
viewController.note = note
default:
print("Unknown Segue")
}
}
}
extension ViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .fade)
}
break;
case .delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
break;
case .update:
if let indexPath = indexPath, let cell = tableView.cellForRow(at: indexPath) {
configureCell(cell, at: indexPath)
}
break;
case .move:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
if let newIndexPath = newIndexPath {
tableView.insertRows(at: [newIndexPath], with: .fade)
}
break;
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = fetchedResultsController.sections else {
return 0
}
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCell", for: indexPath)
// Configure Cell
configureCell(cell, at: indexPath)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
// Fetch Note
let note = fetchedResultsController.object(at: indexPath)
// Delete Note
fetchedResultsController.managedObjectContext.delete(note)
}
func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
// Fetch Note
let note = fetchedResultsController.object(at: indexPath)
// Configure Cell
cell.textLabel?.text = note.title
cell.detailTextLabel?.text = note.content
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension ViewController: AddNoteViewControllerDelegate {
func controller(_ controller: AddNoteViewController, didAddNoteWithTitle title: String) {
// Create Note
let note = Note(context: coreDataManager.managedObjectContext)
// Populate Note
note.content = ""
note.title = title
note.updatedAt = NSDate()
note.createdAt = NSDate()
do {
try note.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print("Unable to Save Note")
print("\(saveError), \(saveError.localizedDescription)")
}
}
}