-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathNotesFRCManager.swift
More file actions
298 lines (247 loc) · 10.6 KB
/
Copy pathNotesFRCManager.swift
File metadata and controls
298 lines (247 loc) · 10.6 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//
// NotesFRCManager.swift
// iOCNotes
//
// Created by Peter Hedlund on 11/5/21.
// Copyright © 2021 Peter Hedlund. All rights reserved.
//
import CoreData
import UIKit
class NotesManager {
let manager: FRCManager<CDNote>
init() {
let request = CDNote.fetchRequest()
request.fetchBatchSize = 288
request.predicate = .allNotes
request.sortDescriptors = [NSSortDescriptor(key: "cdCategory", ascending: true),
NSSortDescriptor(key: "cdModified", ascending: false)]
manager = FRCManager(fetchRequest: request,
managedObjectContext: NotesData.mainThreadContext,
sectionNameKeyPath: "sectionName",
delegate: nil)
}
}
protocol NotesFRCManagerChange {
func applyChanges(tableView: UITableView, animation: UITableView.RowAnimation?)
var insertedRows: [IndexPath] { get }
var deletedRows: [IndexPath] { get }
var updatedRows: [IndexPath] { get }
var insertedSections: IndexSet { get }
var deletedSections: IndexSet { get }
}
protocol FRCManagerDelegate: AnyObject {
func managerDidChangeContent(_ controller: NSObject, change: NotesFRCManagerChange)
}
class FRCSection {
var items = [NSFetchRequestResult]()
init(_ items: [NSFetchRequestResult]) {
self.items = items
}
}
enum FrcDelegateUpdate {
case disable
case enable(withFetch: Bool)
}
struct IndexNote {
var index: IndexPath
var note: CDNote
}
class FRCChange: NotesFRCManagerChange {
var insertedSections = IndexSet()
var deletedSections = IndexSet()
var insertedRows: [IndexPath] {
return insertedElements.map{ $0.index }
}
var deletedRows: [IndexPath] {
return deletedElements.map{ $0.index }
}
var updatedRows: [IndexPath] {
return updatedElements.map{ $0.index }
}
var insertedElements = [IndexNote]()
var deletedElements = [IndexNote]()
var updatedElements = [IndexNote]()
func applyChanges(tableView: UITableView, animation: UITableView.RowAnimation?) {
var filteredUpdatedRows = [IndexPath]()
// the batch update will crash if entered with an invalid index path
// (even if the updated rows are filtered inside the block)
if !updatedRows.isEmpty {
filteredUpdatedRows = updatedRows.filter( { tableView.isValid(indexPath: $0) })
if filteredUpdatedRows.isEmpty {
return
}
}
tableView.performBatchUpdates {
tableView.deleteRows(at: deletedRows, with: animation ?? .fade)
tableView.deleteSections(deletedSections, with: animation ?? .fade)
tableView.insertSections(insertedSections, with: animation ?? .fade)
tableView.insertRows(at: insertedRows, with: animation ?? .fade)
tableView.reloadRows(at: filteredUpdatedRows, with: animation ?? .fade)
} completion: { _ in }
}
}
class FRCManager<ResultType>: NSObject, NSFetchedResultsControllerDelegate where ResultType: NSFetchRequestResult {
weak var delegate: FRCManagerDelegate?
var fetchedResultsController: NSFetchedResultsController<ResultType>
var isSyncing = false
var currentSectionObjectCount = 0
var sections = [FRCSection]()
var disclosureSections: DisclosureSections {
get {
return KeychainHelper.sectionExpandedInfo
}
set {
KeychainHelper.sectionExpandedInfo = newValue
}
}
var fetchedObjectsCount: Int {
return sections.reduce(0, {$0 + $1.items.count})
}
var first: NSFetchRequestResult? {
return sections.first?.items.first
}
var fetchedObjects: [NSFetchRequestResult] {
return sections.flatMap { $0.items }
}
private var currentFRCChange: FRCChange?
func sectionCount() -> Int {
return sections.count
}
func itemCount(in section: Int) -> Int {
return sections[section].items.count
}
func object(at indexPath: IndexPath) -> NSFetchRequestResult {
return sections[indexPath.section].items[indexPath.row]
}
public init(fetchRequest: NSFetchRequest<ResultType>, managedObjectContext context: NSManagedObjectContext, sectionNameKeyPath: String?, delegate: FRCManagerDelegate?) {
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil)
super.init()
fetchedResultsController.delegate = self
self.delegate = delegate
do {
try fetchedResultsController.performFetch()
} catch {
print("Failed to fetch in fetchedResultsControllerManager from core data:\(error)")
}
sections = fetchedResultsController.sections?.compactMap({ $0.objects as? [NSFetchRequestResult]}).compactMap { FRCSection($0) } ?? []
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
currentFRCChange = FRCChange()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
currentFRCChange?.insertedSections.insert(sectionIndex)
var tempDisclosureSections = disclosureSections
tempDisclosureSections.append(DisclosureSection(title: sectionInfo.name, collapsed: false))
disclosureSections = tempDisclosureSections
case .delete:
currentFRCChange?.deletedSections.insert(sectionIndex)
let tempDisclosureSections = disclosureSections
disclosureSections = tempDisclosureSections.filter({ $0.title != sectionInfo.name })
default:
//shouldn't happen
print("FetchedResultsControllerManager didChange atSectionIndex:\(sectionIndex) unknown type:\(type.rawValue)")
return
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if let note = anObject as? CDNote {
let sectionName = note.category == "" ? Constants.noCategory : note.category
switch type {
case .insert:
if let i = newIndexPath {
if let collapsedInfo = disclosureSections.first(where: { $0.title == sectionName }) {
if !collapsedInfo.collapsed {
currentFRCChange?.insertedElements.append(IndexNote(index: i, note: note))
}
}
}
case .delete:
if let i = indexPath {
if let collapsedInfo = disclosureSections.first(where: { $0.title == sectionName }) {
if !collapsedInfo.collapsed {
if isSyncing {
currentFRCChange?.deletedElements.append(IndexNote(index: i, note: note))
} else if currentSectionObjectCount > 1 {
print("Deleting row")
currentFRCChange?.deletedElements.append(IndexNote(index: i, note: note))
}
}
}
}
case .update:
if let i = indexPath {
currentFRCChange?.updatedElements.append(IndexNote(index: i, note: note))
}
case .move:
if let i = indexPath, let sectionCount = controller.sections?.count {
if i.section < sectionCount, let oldSection = controller.sections?[i.section] {
let oldSectionName = oldSection.name
if let collapsedInfo = disclosureSections.first(where: { $0.title == oldSectionName }) {
if !collapsedInfo.collapsed {
currentFRCChange?.deletedElements.append(IndexNote(index: i, note: note))
}
}
}
}
if let i = newIndexPath {
if let collapsedInfo = disclosureSections.first(where: { $0.title == sectionName }) {
if !collapsedInfo.collapsed {
currentFRCChange?.insertedElements.append(IndexNote(index: i, note: note))
}
}
}
@unknown default:
fatalError()
}
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard let change = currentFRCChange else {
return
}
change.insertedElements.sort { $0.index < $1.index }
change.deletedElements.sort { $0.index > $1.index }
change.updatedElements.forEach { indexNote in
sections[indexNote.index.section].items[indexNote.index.row] = indexNote.note
}
change.deletedElements.forEach { indexNote in
sections[indexNote.index.section].items.remove(at: indexNote.index.row)
}
change.deletedSections.reversed().forEach { index in
sections.remove(at: index)
}
change.insertedSections.forEach { index in
sections.insert(FRCSection([NSFetchRequestResult]()), at: index)
}
change.insertedElements.forEach { indexNote in
sections[indexNote.index.section].items.insert(indexNote.note, at: indexNote.index.row)
}
if !change.updatedRows.isEmpty || !change.deletedRows.isEmpty || !change.deletedSections.isEmpty || !change.insertedSections.isEmpty || !change.insertedElements.isEmpty {
delegate?.managerDidChangeContent(self, change: change)
}
currentFRCChange = nil
}
}
extension NSFetchedResultsController {
@objc func validate(indexPath: IndexPath) -> Bool {
if let sections = sections {
if indexPath.section >= sections.count {
return false
}
if indexPath.row >= sections[indexPath.section].numberOfObjects {
return false
}
}
return true
}
}
extension UITableView {
func isValid(indexPath: IndexPath) -> Bool {
return indexPath.section >= 0
&& indexPath.section < self.numberOfSections
&& indexPath.row >= 0
&& indexPath.row < self.numberOfRows(inSection: indexPath.section)
}
}