-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathWPTableViewHandler.m
More file actions
824 lines (691 loc) · 30.1 KB
/
Copy pathWPTableViewHandler.m
File metadata and controls
824 lines (691 loc) · 30.1 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#import "WPTableViewCell.h"
#import "WPTableViewHandler.h"
@import UIKit;
@import CoreData;
@import DesignSystem;
@import WordPressShared;
@import WordPressSharedObjC;
static NSString * const DefaultCellIdentifier = @"DefaultCellIdentifier";
static CGFloat const DefaultCellHeight = 44.0;
@interface WPTableViewHandler ()
@property (nonatomic, strong, readwrite) UITableView *tableView;
@property (nonatomic, strong, readwrite) NSFetchedResultsController *resultsController;
@property (nonatomic, strong) NSIndexPath *indexPathSelectedBeforeUpdates;
@property (nonatomic, strong) NSIndexPath *indexPathSelectedAfterUpdates;
@property (nonatomic, strong) NSMutableArray *sectionHeaders;
@property (nonatomic, strong) NSMutableDictionary *cachedRowHeights;
@property (nonatomic, strong) NSMutableArray *rowsWithInvalidatedHeights;
@property (nonatomic, readwrite) BOOL isScrolling;
@property (nonatomic, strong) NSArray *fetchedResultsBeforeChange;
@property (nonatomic, strong) NSArray *fetchedResultsIndexPathsBeforeChange;
@end
@implementation WPTableViewHandler
#pragma mark - LifeCycle Methods
- (void)dealloc
{
_resultsController.delegate = nil;
_tableView.delegate = nil;
_tableView.dataSource = nil;
}
- (instancetype)initWithTableView:(UITableView *)tableView
{
self = [super init];
if (self) {
_sectionHeaders = [NSMutableArray array];
_cachedRowHeights = [NSMutableDictionary dictionary];
_rowsWithInvalidatedHeights = [NSMutableArray array];
_updateRowAnimation = UITableViewRowAnimationFade;
_insertRowAnimation = UITableViewRowAnimationFade;
_deleteRowAnimation = UITableViewRowAnimationFade;
_moveRowAnimation = UITableViewRowAnimationFade;
_sectionRowAnimation = UITableViewRowAnimationFade;
_tableView = tableView;
_tableView.delegate = self;
_tableView.dataSource = self;
[_tableView registerClass:[WPTableViewCell class] forCellReuseIdentifier:DefaultCellIdentifier];
}
return self;
}
- (BOOL)listensForContentChanges
{
return self.resultsController.delegate != nil;
}
- (void)setListensForContentChanges:(BOOL)listens
{
if (listens) {
self.resultsController.delegate = self;
} else {
self.resultsController.delegate = nil;
}
}
#pragma mark - Public Methods
- (void)clearCachedRowHeights
{
[self.cachedRowHeights removeAllObjects];
}
- (void)refreshTableView
{
[self clearCachedRowHeights];
// If we're not listening for content changes, perform a fetch to ensure content
// is current.
if (![self listensForContentChanges]) {
NSError *error;
[self.resultsController performFetch:&error];
if (error) {
WPLogError(@"TableViewHandler: Error performing fetch while refreshing table view. %@", error);
}
}
[self.tableView reloadData];
}
- (void)refreshTableViewPreservingOffset
{
// Buckle up, refill that coffee...
// Persist some info on the currently visible rows.
[self preserveRowInfoBeforeContentChanges];
// Make sure its necessary to account for currently visible rows.
// We check here vs in `controllerWillChangeContent:` in order to reload
// the table view if necessary.
if ([self.fetchedResultsBeforeChange count] == 0) {
if ([self.delegate respondsToSelector:@selector(tableViewHandlerWillRefreshTableViewPreservingOffset:)]) {
[self.delegate tableViewHandlerWillRefreshTableViewPreservingOffset:self];
}
[self.tableView reloadData];
[self discardPreservedRowInfo];
if ([self.delegate respondsToSelector:@selector(tableViewHandlerDidRefreshTableViewPreservingOffset:)]) {
[self.delegate tableViewHandlerDidRefreshTableViewPreservingOffset:self];
}
// Don't need to do anything else, get out of here.
return;
}
CGPoint originalOffset = self.tableView.contentOffset;
// Get the original visible index paths before reloading data.
NSArray *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];
// Get the original frames for the visible cells.
NSMutableArray <NSValue *> *visibleCellFrames = [NSMutableArray arrayWithCapacity:visibleIndexPaths.count];
for (UITableViewCell *cell in self.tableView.visibleCells) {
[visibleCellFrames addObject:[NSValue valueWithCGRect:cell.frame]];
}
// Notify the delegate that a refresh is about to occur. Allows the delegate
// perform any final clean up, e.g. dismissing a UIRefreshControl.
if ([self.delegate respondsToSelector:@selector(tableViewHandlerWillRefreshTableViewPreservingOffset:)]) {
[self.delegate tableViewHandlerWillRefreshTableViewPreservingOffset:self];
}
// Clear cached heights and reload the tableview
[self refreshTableView];
// Find the new indexPath of the first originally visible object.
// If the first object was deleted, try the next in line of the originally
// visible objects until a match is found.
NSIndexPath *newIndexPath = nil;
CGFloat originalCellOriginOffsetDelta = 0;
int i = 0;
for (NSIndexPath *indexPath in visibleIndexPaths) {
NSInteger index = [self.fetchedResultsIndexPathsBeforeChange indexOfObject:indexPath];
// Fixed a crash that was casued due to index out of bounds.
// `index` is calculated from `fetchedResultsIndexPathsBeforeChange` array
// but used in `fetchedResultsBeforeChange` array which is a misuse.
if (self.fetchedResultsBeforeChange.count <= index) {
break;
}
NSManagedObject *obj = self.fetchedResultsBeforeChange[index];
if (obj.isFault) {
NSError *error;
obj = [self.resultsController.managedObjectContext existingObjectWithID:obj.objectID error:&error];
if (error) {
WPLogError(@"%@, Error %@", NSStringFromSelector(_cmd), error);
}
}
newIndexPath = [self.resultsController indexPathForObject:obj];
if (i >= visibleCellFrames.count) {
break;
}
CGRect originalCellFrame = [[visibleCellFrames objectAtIndex:i] CGRectValue];
if (newIndexPath) {
// Since we still have one of the originally visible objects,
// preserve the original cell frame's origin, relative to the original content offset.
originalCellOriginOffsetDelta += originalOffset.y - originalCellFrame.origin.y;
break;
} else {
originalCellOriginOffsetDelta -= originalCellFrame.size.height;
}
i++;
}
// If none of the previously visible objects exist, find the first object
// preceding the first visible cell instead.
if (!newIndexPath) {
newIndexPath = [self indexPathForFirstObjectPrecedingPreservedVisibleIndexPath:[visibleIndexPaths firstObject]];
}
if (newIndexPath) {
// Trigger a scroll to the cell at the newIndexPath, otherwise it won't have a frame.
[self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
// With the newIndexPath cell in its new position, grab the cell and calculate
// an offset relative to the cell's new origin.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:newIndexPath];
CGPoint newOffset = self.tableView.contentOffset;
newOffset.y = cell.frame.origin.y + originalCellOriginOffsetDelta; // Add the original delta, if any.
// Set the tableview to the new offset
[self.tableView setContentOffset:newOffset];
} else {
// Fail safe. If the new index path was nil set the offset to 0, or the top of the tableView.
[self.tableView setContentOffset:CGPointZero];
}
// Clean up
[self discardPreservedRowInfo];
// Notify the delegate that a refresh has occurred. Allows the delegate
// perform any corrections to the offset, e.g. a negative offset due to a content
// change that was not a post inserted above the previous zero visible index.
if ([self.delegate respondsToSelector:@selector(tableViewHandlerDidRefreshTableViewPreservingOffset:)]) {
[self.delegate tableViewHandlerDidRefreshTableViewPreservingOffset:self];
}
// Whew, take a breather.
}
#pragma mark - Private Methods
- (void)cacheRowHeight:(CGFloat)height forIndexPath:(NSIndexPath *)indexPath
{
[self.cachedRowHeights setObject:@(height) forKey:indexPath];
}
- (CGFloat)cachedRowHeightForIndexPath:(NSIndexPath *)indexPath
{
return [[self.cachedRowHeights objectForKey:indexPath] floatValue];
}
- (void)refreshCachedRowHeightsForWidth:(CGFloat)width
{
if (!self.cacheRowHeights || ![self.delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:forWidth:)]) {
return;
}
NSMutableDictionary *cachedRowHeights = [NSMutableDictionary dictionary];
for (NSObject<NSFetchRequestResult> *obj in self.resultsController.fetchedObjects) {
NSIndexPath *indexPath = [self.resultsController indexPathForObject:obj];
if (!indexPath) {
continue;
}
CGFloat height = [self.delegate tableView:self.tableView heightForRowAtIndexPath:indexPath forWidth:width];
[cachedRowHeights setObject:@(height) forKey:indexPath];
}
self.cachedRowHeights = cachedRowHeights;
}
- (void)clearCachedRowHeightsBelowIndexPath:(NSIndexPath *)indexPath
{
if (!self.cacheRowHeights) {
return;
}
NSMutableArray *invalidKeys = [NSMutableArray array];
for (NSIndexPath *key in [self.cachedRowHeights allKeys]) {
if ([key compare:indexPath] == NSOrderedDescending) {
[invalidKeys addObject:key];
}
}
[self.cachedRowHeights removeObjectForKey:indexPath];
[self.cachedRowHeights removeObjectsForKeys:invalidKeys];
}
- (void)clearCachedRowHeightAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.cacheRowHeights) {
return;
}
[self.cachedRowHeights removeObjectForKey:indexPath];
}
- (void)invalidateCachedRowHeightAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.cacheRowHeights) {
return;
}
NSNumber *height = [self.cachedRowHeights objectForKey:indexPath];
if (!height) {
return;
}
[self.rowsWithInvalidatedHeights addObject:indexPath];
[self clearCachedRowHeightAtIndexPath:indexPath];
}
- (void)resetResultsController
{
_resultsController = nil;
}
#pragma mark - Required Delegate Methods
- (NSManagedObjectContext *)managedObjectContext
{
return [self.delegate managedObjectContext];
}
- (NSFetchRequest *)fetchRequest
{
return [self.delegate fetchRequest];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
[self.delegate configureCell:cell atIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.delegate tableView:tableView didSelectRowAtIndexPath:indexPath];
}
- (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point {
if ([self.delegate respondsToSelector:@selector(tableView:contextMenuConfigurationForRowAtIndexPath:point:)]) {
return [self.delegate tableView:tableView contextMenuConfigurationForRowAtIndexPath:indexPath point:point];
}
return nil;
}
#pragma mark - Optional Delegate Methods
- (NSString *)sectionNameKeyPath
{
if ([self.delegate respondsToSelector:@selector(sectionNameKeyPath)]) {
return [self.delegate sectionNameKeyPath];
}
return nil;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:canEditRowAtIndexPath:)]) {
return [self.delegate tableView:tableView canEditRowAtIndexPath:indexPath];
}
return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:commitEditingStyle:forRowAtIndexPath:)]) {
[self.delegate tableView:tableView commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:editingStyleForRowAtIndexPath:)]) {
return [self.delegate tableView:tableView editingStyleForRowAtIndexPath:indexPath];
}
return UITableViewCellEditingStyleNone;
}
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:leadingSwipeActionsConfigurationForRowAtIndexPath:)]) {
return [self.delegate tableView:tableView leadingSwipeActionsConfigurationForRowAtIndexPath:indexPath];
}
return nil;
}
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:trailingSwipeActionsConfigurationForRowAtIndexPath:)]) {
return [self.delegate tableView:tableView trailingSwipeActionsConfigurationForRowAtIndexPath:indexPath];
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:cellForRowAtIndexPath:)]) {
return [self.delegate tableView:tableView cellForRowAtIndexPath:indexPath];
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
if (self.tableView.isEditing) {
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:)]) {
return [self.delegate tableView:tableView titleForDeleteConfirmationButtonForRowAtIndexPath:indexPath];
}
return nil;
}
- (void)deletingSelectedRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(deletingSelectedRowAtIndexPath:)]) {
[self.delegate deletingSelectedRowAtIndexPath:indexPath];
}
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat height = DefaultCellHeight;
if (self.cacheRowHeights) {
height = [self cachedRowHeightForIndexPath:indexPath];
if (height) {
return height;
}
if ([self.rowsWithInvalidatedHeights containsObject:indexPath]) {
// Recompute and return the real height. It will end up in the cache automatically.
[self.rowsWithInvalidatedHeights removeObject:indexPath];
height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
return height;
}
}
if ([self.delegate respondsToSelector:@selector(tableView:estimatedHeightForRowAtIndexPath:)]) {
height = [self.delegate tableView:tableView estimatedHeightForRowAtIndexPath:indexPath];
}
return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat height = DefaultCellHeight;
if (self.cacheRowHeights) {
height = [self cachedRowHeightForIndexPath:indexPath];
if (height) {
return height;
}
}
if ([self.delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {
height = [self.delegate tableView:tableView heightForRowAtIndexPath:indexPath];
if (self.cacheRowHeights) {
[self cacheRowHeight:height forIndexPath:indexPath];
}
}
return height;
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:shouldHighlightRowAtIndexPath:)]) {
return [self.delegate tableView:tableView shouldHighlightRowAtIndexPath:indexPath];
}
return YES;
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) {
[self.delegate tableView:tableView willSelectRowAtIndexPath:indexPath];
}
return indexPath;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:willDisplayCell:forRowAtIndexPath:)]) {
[self.delegate tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
}
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(tableView:didEndDisplayingCell:forRowAtIndexPath:)]) {
[self.delegate tableView:tableView didEndDisplayingCell:cell forRowAtIndexPath:indexPath];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
return [self.delegate tableView:tableView viewForHeaderInSection:section];
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
return [self.delegate tableView:tableView heightForHeaderInSection:section];
}
return UITableViewAutomaticDimension;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
return [self.delegate tableView:tableView viewForFooterInSection:section];
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:heightForFooterInSection:)]) {
return [self.delegate tableView:tableView heightForFooterInSection:section];
}
return UITableViewAutomaticDimension;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:willDisplayHeaderView:forSection:)]) {
[self.delegate tableView:tableView willDisplayHeaderView:view forSection:section];
}
}
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:willDisplayFooterView:forSection:)]) {
[self.delegate tableView:tableView willDisplayFooterView:view forSection:section];
} else {
if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView *footerView = (UITableViewHeaderFooterView *)view;
UILabel *textLabel = footerView.textLabel;
if (textLabel.isUserInteractionEnabled) {
textLabel.textColor = ObjCBridge_UIAppColor.primary;
}
}
}
}
#pragma mark - TableView Datasource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.resultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *sections = [self.resultsController sections];
if ([sections count] == 0) {
return 0;
}
id <NSFetchedResultsSectionInfo> sectionInfo = nil;
sectionInfo = [sections objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
return [self.delegate tableView:tableView titleForHeaderInSection:section];
}
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.resultsController sections] objectAtIndex:section];
return [sectionInfo name];
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(tableView:titleForFooterInSection:)]) {
return [self.delegate tableView:tableView titleForFooterInSection:section];
}
return nil;
}
#pragma mark - UIScrollViewDelegate Methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
self.isScrolling = YES;
if ([self.delegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
[self.delegate scrollViewWillBeginDragging:scrollView];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
self.isScrolling = NO;
if ([self.delegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) {
[self.delegate scrollViewDidEndDecelerating:scrollView];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if ([self.delegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
[self.delegate scrollViewDidScroll:scrollView];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
self.isScrolling = decelerate;
if ([self.delegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) {
[self.delegate scrollViewDidEndDragging:scrollView willDecelerate:(BOOL)decelerate];
}
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
if ([self.delegate respondsToSelector:@selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:)]) {
[self.delegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
}
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)resultsController
{
if (_resultsController != nil) {
return _resultsController;
}
NSFetchRequest *fetchRequest = [self fetchRequest];
if (!fetchRequest) {
return nil;
}
NSManagedObjectContext *moc = [self managedObjectContext];
_resultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:[self fetchRequest]
managedObjectContext:moc
sectionNameKeyPath:[self sectionNameKeyPath]
cacheName:nil];
_resultsController.delegate = self;
NSError *error = nil;
if (![_resultsController performFetch:&error]) {
WPLogError(@"%@ couldn't fetch %@: %@", self, [[self fetchRequest] entityName], [error localizedDescription]);
_resultsController = nil;
}
return _resultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
if ([self.delegate respondsToSelector:@selector(tableViewWillChangeContent:)]) {
[self.delegate tableViewWillChangeContent:self.tableView];
}
self.indexPathSelectedBeforeUpdates = [self.tableView indexPathForSelectedRow];
if (self.disableAnimations) {
[UIView setAnimationsEnabled:NO];
}
[self.tableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// Catch unexpected expections when ending tableView updates to prevent crashes
NSError *error;
[WPException objcTryBlock:^{
[self.tableView endUpdates];
if (self.disableAnimations) {
[UIView setAnimationsEnabled:YES];
}
} error:&error];
if (error) {
WPLogError(@"TableViewHandler: Error ending updates %@", error);
[self refreshTableView];
return;
}
// Prevent crashes in iOS 14 if the row is negative
// See http://git.io/JIKIB
if (self.indexPathSelectedAfterUpdates && self.indexPathSelectedAfterUpdates.row > 0) {
[self.tableView selectRowAtIndexPath:self.indexPathSelectedAfterUpdates animated:NO scrollPosition:UITableViewScrollPositionNone];
} else if (self.indexPathSelectedBeforeUpdates && self.indexPathSelectedBeforeUpdates.row > 0) {
[self.tableView selectRowAtIndexPath:self.indexPathSelectedBeforeUpdates animated:NO scrollPosition:UITableViewScrollPositionNone];
}
self.indexPathSelectedBeforeUpdates = nil;
self.indexPathSelectedAfterUpdates = nil;
if ([self.delegate respondsToSelector:@selector(tableViewDidChangeContent:)]) {
[self.delegate tableViewDidChangeContent:self.tableView];
}
}
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
// Prevent crashes in iOS 14 if the row is negative
// See http://git.io/JIKIB
if (indexPath.row < 0 || newIndexPath.row < 0) {
return;
}
// Prevents a crash where index path rows could end with an integer overflow error.
// See https://github.com/wordpress-mobile/WordPress-iOS/issues/15366
if (indexPath.row == NSUIntegerMax || newIndexPath.row == NSUIntegerMax) {
return;
}
if (NSFetchedResultsChangeUpdate == type && newIndexPath && ![newIndexPath isEqual:indexPath]) {
// Seriously, Apple?
// http://developer.apple.com/library/ios/#releasenotes/iPhone/NSFetchedResultsChangeMoveReportedAsNSFetchedResultsChangeUpdate/_index.html
type = NSFetchedResultsChangeMove;
}
if (newIndexPath == nil) {
// It seems in some cases newIndexPath can be nil for updates
newIndexPath = indexPath;
}
switch(type) {
case NSFetchedResultsChangeInsert:
{
[self clearCachedRowHeightsBelowIndexPath:newIndexPath];
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:self.insertRowAnimation];
}
break;
case NSFetchedResultsChangeDelete:
{
[self clearCachedRowHeightsBelowIndexPath:indexPath];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:self.deleteRowAnimation];
if ([self.indexPathSelectedBeforeUpdates isEqual:indexPath]) {
[self deletingSelectedRowAtIndexPath:indexPath];
}
}
break;
case NSFetchedResultsChangeUpdate:
{
BOOL shouldCancelUpdateAnimation =
[self.delegate respondsToSelector:@selector(shouldCancelUpdateAnimation)]
&& [self.delegate shouldCancelUpdateAnimation];
if (!shouldCancelUpdateAnimation) {
[self invalidateCachedRowHeightAtIndexPath:indexPath];
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:self.updateRowAnimation];
}
}
break;
case NSFetchedResultsChangeMove:
{
NSIndexPath *lowerIndexPath = indexPath;
if ([indexPath compare:newIndexPath] == NSOrderedDescending) {
lowerIndexPath = newIndexPath;
}
[self clearCachedRowHeightsBelowIndexPath:lowerIndexPath];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:self.moveRowAnimation];
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:self.moveRowAnimation];
if ([self.indexPathSelectedBeforeUpdates isEqual:indexPath] && self.indexPathSelectedAfterUpdates == nil) {
self.indexPathSelectedAfterUpdates = newIndexPath;
}
}
break;
default:
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
if (type == NSFetchedResultsChangeInsert) {
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:self.sectionRowAnimation];
} else if (type == NSFetchedResultsChangeDelete) {
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:self.sectionRowAnimation];
}
}
#pragma mark - Refresh and Preserve Offset Methods
- (void)preserveRowInfoBeforeContentChanges
{
self.fetchedResultsBeforeChange = [[self.resultsController fetchedObjects] copy];
NSIndexPath *lastVisibleIndexPath = [[self.tableView indexPathsForVisibleRows] lastObject];
NSMutableArray *indexPaths = [NSMutableArray array];
for (NSManagedObject *object in self.fetchedResultsBeforeChange) {
NSIndexPath *indexPath = [self.resultsController indexPathForObject:object];
if (!indexPath) {
continue;
}
// Only preserve info relevant to the current scroll offset. Anything else is extra work.
NSComparisonResult order = [indexPath compare:lastVisibleIndexPath];
if (order == NSOrderedDescending) {
continue;
}
[indexPaths addObject:indexPath];
}
self.fetchedResultsIndexPathsBeforeChange = indexPaths;
}
- (NSIndexPath *)indexPathForFirstObjectPrecedingPreservedVisibleIndexPath:(NSIndexPath *)indexPath
{
NSInteger index = [self.fetchedResultsIndexPathsBeforeChange indexOfObject:indexPath];
if (NSNotFound == index) {
return nil;
}
NSArray *arr = [self.fetchedResultsIndexPathsBeforeChange subarrayWithRange:NSMakeRange(0, index)];
for (NSInteger i = [arr count] -1; i > 0; i-- ) {
NSManagedObject *obj = self.fetchedResultsBeforeChange[i];
NSIndexPath *newIndexPath = [self.resultsController indexPathForObject:obj];
if (newIndexPath) {
return newIndexPath;
}
}
return nil;
}
- (void)discardPreservedRowInfo
{
self.fetchedResultsBeforeChange = nil;
self.fetchedResultsIndexPathsBeforeChange = nil;
}
@end