forked from RestKit/RestKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RKAbstractTableController.m
executable file
·1362 lines (1145 loc) · 56.8 KB
/
RKAbstractTableController.m
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// RKAbstractTableController.m
// RestKit
//
// Created by Jeff Arena on 8/11/11.
// Copyright (c) 2011 RestKit.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "RKAbstractTableController.h"
#import "RKAbstractTableController_Internals.h"
#import "RKObjectMappingOperation.h"
#import "RKLog.h"
#import "RKErrors.h"
#import "RKReachabilityObserver.h"
#import "UIView+FindFirstResponder.h"
// Define logging component
#undef RKLogComponent
#define RKLogComponent lcl_cRestKitUI
/**
Bounce pixels define how many pixels the cell swipe view is
moved during the bounce animation
*/
#define BOUNCE_PIXELS 5.0
NSString* const RKTableControllerDidStartLoadNotification = @"RKTableControllerDidStartLoadNotification";
NSString* const RKTableControllerDidFinishLoadNotification = @"RKTableControllerDidFinishLoadNotification";
NSString* const RKTableControllerDidLoadObjectsNotification = @"RKTableControllerDidLoadObjectsNotification";
NSString* const RKTableControllerDidLoadEmptyNotification = @"RKTableControllerDidLoadEmptyNotification";
NSString* const RKTableControllerDidLoadErrorNotification = @"RKTableControllerDidLoadErrorNotification";
NSString* const RKTableControllerDidBecomeOnline = @"RKTableControllerDidBecomeOnline";
NSString* const RKTableControllerDidBecomeOffline = @"RKTableControllerDidBecomeOffline";
static NSString* lastUpdatedDateDictionaryKey = @"lastUpdatedDateDictionaryKey";
@implementation RKAbstractTableController
@synthesize delegate = _delegate;
@synthesize viewController = _viewController;
@synthesize tableView = _tableView;
@synthesize sections = _sections;
@synthesize defaultRowAnimation = _defaultRowAnimation;
@synthesize objectLoader = _objectLoader;
@synthesize objectManager = _objectManager;
@synthesize cellMappings = _cellMappings;
@synthesize autoRefreshFromNetwork = _autoRefreshFromNetwork;
@synthesize autoRefreshRate = _autoRefreshRate;
@synthesize empty = _empty;
@synthesize loading = _loading;
@synthesize loaded = _loaded;
@synthesize online = _online;
@synthesize error = _error;
@synthesize imageForEmpty = _imageForEmpty;
@synthesize imageForError = _imageForError;
@synthesize imageForOffline = _imageForOffline;
@synthesize loadingView = _loadingView;
@synthesize variableHeightRows = _variableHeightRows;
@synthesize showsHeaderRowsWhenEmpty = _showsHeaderRowsWhenEmpty;
@synthesize showsFooterRowsWhenEmpty = _showsFooterRowsWhenEmpty;
@synthesize pullToRefreshEnabled = _pullToRefreshEnabled;
@synthesize headerItems = _headerItems;
@synthesize footerItems = _footerItems;
@synthesize canEditRows = _canEditRows;
@synthesize canMoveRows = _canMoveRows;
@synthesize autoResizesForKeyboard = _autoResizesForKeyboard;
@synthesize emptyItem = _emptyItem;
@synthesize cellSwipeViewsEnabled = _cellSwipeViewsEnabled;
@synthesize cellSwipeView = _cellSwipeView;
@synthesize swipeCell = _swipeCell;
@synthesize animatingCellSwipe = _animatingCellSwipe;
@synthesize swipeDirection = _swipeDirection;
@synthesize swipeObject = _swipeObject;
@synthesize showsOverlayImagesModally = _modalOverlay;
@synthesize overlayFrame = _overlayFrame;
@synthesize tableOverlayView = _tableOverlayView;
@synthesize stateOverlayImageView = _stateOverlayImageView;
@synthesize cache = _cache;
#pragma mark - Instantiation
+ (id)tableControllerWithTableView:(UITableView*)tableView
forViewController:(UIViewController*)viewController {
return [[[self alloc] initWithTableView:tableView viewController:viewController] autorelease];
}
+ (id)tableControllerForTableViewController:(UITableViewController*)tableViewController {
return [self tableControllerWithTableView:tableViewController.tableView
forViewController:tableViewController];
}
- (id)initWithTableView:(UITableView*)theTableView viewController:(UIViewController*)theViewController {
NSAssert(theTableView, @"Cannot initialize a table view model with a nil tableView");
NSAssert(theViewController, @"Cannot initialize a table view model with a nil viewController");
self = [self init];
if (self) {
self.tableView = theTableView;
self.viewController = theViewController;
self.variableHeightRows = NO;
self.defaultRowAnimation = UITableViewRowAnimationFade;
self.overlayFrame = CGRectZero;
self.showsOverlayImagesModally = YES;
}
return self;
}
- (id)init {
self = [super init];
if (self) {
if ([self isMemberOfClass:[RKAbstractTableController class]]) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:[NSString stringWithFormat:@"%@ is abstract. Instantiate one its subclasses instead.",
NSStringFromClass([self class])]
userInfo:nil];
}
_sections = [NSMutableArray new];
self.objectManager = [RKObjectManager sharedManager];
_cellMappings = [RKTableViewCellMappings new];
_headerItems = [NSMutableArray new];
_footerItems = [NSMutableArray new];
_showsHeaderRowsWhenEmpty = YES;
_showsFooterRowsWhenEmpty = YES;
// Setup autoRefreshRate to (effectively) never
_autoRefreshFromNetwork = NO;
_autoRefreshRate = NSTimeIntervalSince1970;
// Setup key-value observing
[self addObserver:self
forKeyPath:@"loading"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
[self addObserver:self
forKeyPath:@"loaded"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
[self addObserver:self
forKeyPath:@"empty"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
[self addObserver:self
forKeyPath:@"error"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
[self addObserver:self
forKeyPath:@"online"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
}
return self;
}
- (void)dealloc {
// Disconnect from the tableView
if (_tableView.delegate == self) _tableView.delegate = nil;
if (_tableView.dataSource == self) _tableView.dataSource = nil;
_tableView = nil;
// Remove overlay and pull-to-refresh subviews
[_stateOverlayImageView removeFromSuperview];
[_stateOverlayImageView release];
_stateOverlayImageView = nil;
[_tableOverlayView removeFromSuperview];
[_tableOverlayView release];
_tableOverlayView = nil;
[_pullToRefreshHeaderView removeFromSuperview];
_pullToRefreshHeaderView = nil;
// Remove observers
[self removeObserver:self forKeyPath:@"loading"];
[self removeObserver:self forKeyPath:@"loaded"];
[self removeObserver:self forKeyPath:@"empty"];
[self removeObserver:self forKeyPath:@"error"];
[self removeObserver:self forKeyPath:@"online"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
// TODO: WTF? Get UI crashes when enabled...
// [_objectManager.requestQueue abortRequestsWithDelegate:self];
_objectLoader.delegate = nil;
_objectLoader = nil;
[_sections release];
[_cellMappings release];
[_headerItems release];
[_footerItems release];
[_cellSwipeView release];
[_swipeCell release];
[_swipeObject release];
[_emptyItem release];
[super dealloc];
}
- (void)setTableView:(UITableView *)tableView {
NSAssert(tableView, @"Cannot assign a nil tableView to the model");
_tableView = tableView;
_tableView.delegate = self;
_tableView.dataSource = self;
}
- (void)setViewController:(UIViewController *)viewController {
_viewController = viewController;
if ([viewController isKindOfClass:[UITableViewController class]]) {
self.tableView = [(UITableViewController*)viewController tableView];
}
}
- (void)setObjectManager:(RKObjectManager *)objectManager {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
// Remove observers
if (_objectManager) {
[notificationCenter removeObserver:self
name:RKObjectManagerDidBecomeOfflineNotification
object:_objectManager];
[notificationCenter removeObserver:self
name:RKObjectManagerDidBecomeOnlineNotification
object:_objectManager];
}
_objectManager = objectManager;
// Set observers
[notificationCenter addObserver:self
selector:@selector(objectManagerConnectivityDidChange:)
name:RKObjectManagerDidBecomeOnlineNotification
object:objectManager];
[notificationCenter addObserver:self
selector:@selector(objectManagerConnectivityDidChange:)
name:RKObjectManagerDidBecomeOfflineNotification
object:objectManager];
// Initialize online/offline state (if it is known)
if (objectManager.networkStatus != RKObjectManagerNetworkStatusUnknown) {
self.online = objectManager.isOnline;
}
}
- (void)setAutoResizesForKeyboard:(BOOL)autoResizesForKeyboard {
if (_autoResizesForKeyboard != autoResizesForKeyboard) {
_autoResizesForKeyboard = autoResizesForKeyboard;
if (_autoResizesForKeyboard) {
// Register for Keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(resizeTableViewForKeyboard:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(resizeTableViewForKeyboard:)
name:UIKeyboardWillHideNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
}
}
- (void)setAutoRefreshFromNetwork:(BOOL)autoRefreshFromNetwork {
if (_autoRefreshFromNetwork != autoRefreshFromNetwork) {
_autoRefreshFromNetwork = autoRefreshFromNetwork;
if (_autoRefreshFromNetwork) {
NSString* cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:@"RKAbstractTableControllerCache"];
_cache = [[RKCache alloc] initWithPath:cachePath subDirectories:nil];
} else {
if (_cache) {
[_cache invalidateAll];
[_cache release];
_cache = nil;
}
}
}
}
- (void)objectManagerConnectivityDidChange:(NSNotification *)notification {
RKLogTrace(@"%@ received network status change notification: %@", self, [notification name]);
self.online = self.objectManager.isOnline;
}
#pragma mark - Managing Sections
- (NSUInteger)sectionCount {
return [_sections count];
}
- (NSUInteger)rowCount {
return [[_sections valueForKeyPath:@"@sum.rowCount"] intValue];
}
- (RKTableSection *)sectionAtIndex:(NSUInteger)index {
return [_sections objectAtIndex:index];
}
- (NSUInteger)indexForSection:(RKTableSection *)section {
NSAssert(section, @"Cannot return index for a nil section");
return [_sections indexOfObject:section];
}
- (RKTableSection *)sectionWithHeaderTitle:(NSString *)title {
for (RKTableSection* section in _sections) {
if ([section.headerTitle isEqualToString:title]) {
return section;
}
}
return nil;
}
- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath {
RKTableSection* section = [self sectionAtIndex:indexPath.section];
id mappableObject = [section objectAtIndex:indexPath.row];
RKTableViewCellMapping* cellMapping = [self.cellMappings cellMappingForObject:mappableObject];
NSAssert(cellMapping, @"Cannot build a tableView cell for object %@: No cell mapping defined for objects of type '%@'", mappableObject, NSStringFromClass([mappableObject class]));
UITableViewCell* cell = [cellMapping mappableObjectForData:self.tableView];
NSAssert(cell, @"Cell mapping failed to dequeue or allocate a tableViewCell for object: %@", mappableObject);
// Map the object state into the cell
RKObjectMappingOperation* mappingOperation = [[RKObjectMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:cell mapping:cellMapping];
NSError* error = nil;
BOOL success = [mappingOperation performMapping:&error];
[mappingOperation release];
// NOTE: If there is no mapping work performed, but no error is generated then
// we consider the operation a success. It is common for table cells to not contain
// any dynamically mappable content (i.e. header/footer rows, banners, etc.)
if (success == NO && error != nil) {
RKLogError(@"Failed to generate table cell for object: %@", error);
return nil;
}
return cell;
}
#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)theTableView {
NSAssert(theTableView == self.tableView, @"numberOfSectionsInTableView: invoked with inappropriate tableView: %@", theTableView);
RKLogTrace(@"%@ numberOfSectionsInTableView = %d", self, self.sectionCount);
return self.sectionCount;
}
- (NSInteger)tableView:(UITableView*)theTableView numberOfRowsInSection:(NSInteger)section {
NSAssert(theTableView == self.tableView, @"tableView:numberOfRowsInSection: invoked with inappropriate tableView: %@", theTableView);
RKLogTrace(@"%@ numberOfRowsInSection:%d = %d", self, section, self.sectionCount);
return [[_sections objectAtIndex:section] rowCount];
}
- (UITableViewCell *)tableView:(UITableView*)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(theTableView == self.tableView, @"tableView:cellForRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView);
UITableViewCell* cell = [self cellForObjectAtIndexPath:indexPath];
RKLogTrace(@"%@ cellForRowAtIndexPath:%@ = %@", self, indexPath, cell);
return cell;
}
- (NSString*)tableView:(UITableView*)theTableView titleForHeaderInSection:(NSInteger)section {
NSAssert(theTableView == self.tableView, @"tableView:titleForHeaderInSection: invoked with inappropriate tableView: %@", theTableView);
return [[_sections objectAtIndex:section] headerTitle];
}
- (NSString*)tableView:(UITableView*)theTableView titleForFooterInSection:(NSInteger)section {
NSAssert(theTableView == self.tableView, @"tableView:titleForFooterInSection: invoked with inappropriate tableView: %@", theTableView);
return [[_sections objectAtIndex:section] footerTitle];
}
- (BOOL)tableView:(UITableView*)theTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(theTableView == self.tableView, @"tableView:canEditRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView);
return _canEditRows;
}
- (BOOL)tableView:(UITableView*)theTableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(theTableView == self.tableView, @"tableView:canMoveRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView);
return _canMoveRows;
}
#pragma mark - Cell Mappings
- (void)mapObjectsWithClass:(Class)objectClass toTableCellsWithMapping:(RKTableViewCellMapping*)cellMapping {
// TODO: Should we raise an exception/throw a warning if you are doing class mapping for a type
// that implements a cellMapping instance method? Maybe a class declaration overrides
[_cellMappings setCellMapping:cellMapping forClass:objectClass];
}
- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(indexPath, @"Cannot lookup object with a nil indexPath");
RKTableSection* section = [self sectionAtIndex:indexPath.section];
return [section objectAtIndex:indexPath.row];
}
- (RKTableViewCellMapping*)cellMappingForObjectAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(indexPath, @"Cannot lookup cell mapping for object with a nil indexPath");
id object = [self objectForRowAtIndexPath:indexPath];
return [self.cellMappings cellMappingForObject:object];
}
- (UITableViewCell *)cellForObject:(id)object {
NSIndexPath *indexPath = [self indexPathForObject:object];
return indexPath ? [self cellForObjectAtIndexPath:indexPath] : nil;
}
// TODO: unit test...
// TODO: This needs to be updated to take into account header & footer rows...
- (NSIndexPath *)indexPathForObject:(id)object {
NSUInteger sectionIndex = 0;
for (RKTableSection *section in self.sections) {
NSUInteger rowIndex = 0;
for (id rowObject in section.objects) {
if ([rowObject isEqual:object]) {
return [NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex];
}
rowIndex++;
}
sectionIndex++;
}
return nil;
}
#pragma mark - Header and Footer Rows
- (void)addHeaderRowForItem:(RKTableItem*)tableItem {
[_headerItems addObject:tableItem];
}
- (void)addFooterRowForItem:(RKTableItem*)tableItem {
[_footerItems addObject:tableItem];
}
- (void)addHeaderRowWithMapping:(RKTableViewCellMapping *)cellMapping {
RKTableItem* tableItem = [RKTableItem tableItem];
tableItem.cellMapping = cellMapping;
[self addHeaderRowForItem:tableItem];
}
- (void)addFooterRowWithMapping:(RKTableViewCellMapping *)cellMapping {
RKTableItem* tableItem = [RKTableItem tableItem];
tableItem.cellMapping = cellMapping;
[self addFooterRowForItem:tableItem];
}
- (void)removeAllHeaderRows {
[_headerItems removeAllObjects];
}
- (void)removeAllFooterRows {
[_footerItems removeAllObjects];
}
#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView*)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(theTableView == self.tableView, @"tableView:didSelectRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView);
RKLogTrace(@"%@: Row at indexPath %@ selected for tableView %@", self, indexPath, theTableView);
id object = [self objectForRowAtIndexPath:indexPath];
// NOTE: Do NOT use cellForObjectAtIndexPath here. See https://gist.github.com/eafbb641d37bb7137759
UITableViewCell* cell = [theTableView cellForRowAtIndexPath:indexPath];
RKTableViewCellMapping* cellMapping = [_cellMappings cellMappingForObject:object];
// NOTE: Handle deselection first as the onSelectCell processing may result in the tableView
// being reloaded and our instances invalidated
if (cellMapping.deselectsRowOnSelection) {
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
if (cellMapping.onSelectCell) {
cellMapping.onSelectCell();
}
if (cellMapping.onSelectCellForObjectAtIndexPath) {
RKLogTrace(@"%@: Invoking onSelectCellForObjectAtIndexPath block with cellMapping %@ for object %@ at indexPath = %@", self, cell, object, indexPath);
cellMapping.onSelectCellForObjectAtIndexPath(cell, object, indexPath);
}
}
- (void)tableView:(UITableView *)theTableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSAssert(theTableView == self.tableView, @"tableView:didSelectRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView);
cell.hidden = NO;
id mappableObject = [self objectForRowAtIndexPath:indexPath];
RKTableViewCellMapping* cellMapping = [self.cellMappings cellMappingForObject:mappableObject];
if (cellMapping.onCellWillAppearForObjectAtIndexPath) {
cellMapping.onCellWillAppearForObjectAtIndexPath(cell, mappableObject, indexPath);
}
// Informal protocol
// TODO: Needs documentation!!!
SEL willDisplaySelector = @selector(willDisplayInTableViewCell:);
if ([mappableObject respondsToSelector:willDisplaySelector]) {
[mappableObject performSelector:willDisplaySelector withObject:cell];
}
// Handle hiding header/footer rows when empty
if ([self isEmpty]) {
if (! self.showsHeaderRowsWhenEmpty && [_headerItems containsObject:mappableObject]) {
cell.hidden = YES;
}
if (! self.showsFooterRowsWhenEmpty && [_footerItems containsObject:mappableObject]) {
cell.hidden = YES;
}
} else {
if (self.emptyItem && [self.emptyItem isEqual:mappableObject]) {
cell.hidden = YES;
}
}
}
// Variable height support
- (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.variableHeightRows) {
RKTableViewCellMapping* cellMapping = [self cellMappingForObjectAtIndexPath:indexPath];
if (cellMapping.heightOfCellForObjectAtIndexPath) {
id object = [self objectForRowAtIndexPath:indexPath];
CGFloat height = cellMapping.heightOfCellForObjectAtIndexPath(object, indexPath);
RKLogTrace(@"Variable row height configured for tableView. Height via block invocation for row at indexPath '%@' = %f", indexPath, cellMapping.rowHeight);
return height;
} else {
RKLogTrace(@"Variable row height configured for tableView. Height for row at indexPath '%@' = %f", indexPath, cellMapping.rowHeight);
return cellMapping.rowHeight;
}
}
RKLogTrace(@"Uniform row height configured for tableView. Table view row height = %f", self.tableView.rowHeight);
return self.tableView.rowHeight;
}
- (CGFloat)tableView:(UITableView*)theTableView heightForHeaderInSection:(NSInteger)sectionIndex {
NSAssert(theTableView == self.tableView, @"heightForHeaderInSection: invoked with inappropriate tableView: %@", theTableView);
RKTableSection* section = [self sectionAtIndex:sectionIndex];
return section.headerHeight;
}
- (CGFloat)tableView:(UITableView*)theTableView heightForFooterInSection:(NSInteger)sectionIndex {
NSAssert(theTableView == self.tableView, @"heightForFooterInSection: invoked with inappropriate tableView: %@", theTableView);
RKTableSection* section = [self sectionAtIndex:sectionIndex];
return section.footerHeight;
}
- (UIView*)tableView:(UITableView*)theTableView viewForHeaderInSection:(NSInteger)sectionIndex {
NSAssert(theTableView == self.tableView, @"viewForHeaderInSection: invoked with inappropriate tableView: %@", theTableView);
RKTableSection* section = [self sectionAtIndex:sectionIndex];
return section.headerView;
}
- (UIView*)tableView:(UITableView*)theTableView viewForFooterInSection:(NSInteger)sectionIndex {
NSAssert(theTableView == self.tableView, @"viewForFooterInSection: invoked with inappropriate tableView: %@", theTableView);
RKTableSection* section = [self sectionAtIndex:sectionIndex];
return section.footerView;
}
- (void)tableView:(UITableView*)theTableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
RKTableViewCellMapping* cellMapping = [self cellMappingForObjectAtIndexPath:indexPath];
if (cellMapping.onTapAccessoryButtonForObjectAtIndexPath) {
RKLogTrace(@"Found a block for tableView:accessoryButtonTappedForRowWithIndexPath: Executing...");
UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
id object = [self objectForRowAtIndexPath:indexPath];
cellMapping.onTapAccessoryButtonForObjectAtIndexPath(cell, object, indexPath);
}
}
- (NSString*)tableView:(UITableView*)theTableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
RKTableViewCellMapping* cellMapping = [self cellMappingForObjectAtIndexPath:indexPath];
if (cellMapping.titleForDeleteButtonForObjectAtIndexPath) {
RKLogTrace(@"Found a block for tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: Executing...");
UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
id object = [self objectForRowAtIndexPath:indexPath];
return cellMapping.titleForDeleteButtonForObjectAtIndexPath(cell, object, indexPath);
}
return NSLocalizedString(@"Delete", nil);
}
- (UITableViewCellEditingStyle)tableView:(UITableView*)theTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
if (_canEditRows) {
RKTableViewCellMapping* cellMapping = [self cellMappingForObjectAtIndexPath:indexPath];
UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
if (cellMapping.editingStyleForObjectAtIndexPath) {
RKLogTrace(@"Found a block for tableView:editingStyleForRowAtIndexPath: Executing...");
id object = [self objectForRowAtIndexPath:indexPath];
return cellMapping.editingStyleForObjectAtIndexPath(cell, object, indexPath);
}
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView*)theTableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.delegate respondsToSelector:@selector(tableController:didEndEditing:atIndexPath:)]) {
id object = [self objectForRowAtIndexPath:indexPath];
[self.delegate tableController:self didEndEditing:object atIndexPath:indexPath];
}
}
- (void)tableView:(UITableView*)theTableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.delegate respondsToSelector:@selector(tableController:willBeginEditing:atIndexPath:)]) {
id object = [self objectForRowAtIndexPath:indexPath];
[self.delegate tableController:self willBeginEditing:object atIndexPath:indexPath];
}
}
- (NSIndexPath *)tableView:(UITableView*)theTableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
if (_canMoveRows) {
RKTableViewCellMapping* cellMapping = [self cellMappingForObjectAtIndexPath:sourceIndexPath];
if (cellMapping.targetIndexPathForMove) {
RKLogTrace(@"Found a block for tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath: Executing...");
UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:sourceIndexPath];
id object = [self objectForRowAtIndexPath:sourceIndexPath];
return cellMapping.targetIndexPathForMove(cell, object, sourceIndexPath, proposedDestinationIndexPath);
}
}
return proposedDestinationIndexPath;
}
- (NSIndexPath *)tableView:(UITableView*)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self removeSwipeView:YES];
return indexPath;
}
#pragma mark - Network Table Loading
- (void)cancelLoad {
[self.objectLoader cancel];
}
- (NSDate*)lastUpdatedDate {
if (! self.objectLoader) {
return nil;
}
if (_autoRefreshFromNetwork) {
NSAssert(_cache, @"Found a nil cache when trying to read our last loaded time");
NSDictionary* lastUpdatedDates = [_cache dictionaryForCacheKey:lastUpdatedDateDictionaryKey];
RKLogTrace(@"Last updated dates dictionary retrieved from tableController cache: %@", lastUpdatedDates);
if (lastUpdatedDates) {
NSString* absoluteURLString = [self.objectLoader.URL absoluteString];
NSNumber* lastUpdatedTimeIntervalSince1970 = (NSNumber*)[lastUpdatedDates objectForKey:absoluteURLString];
if (absoluteURLString && lastUpdatedTimeIntervalSince1970) {
return [NSDate dateWithTimeIntervalSince1970:[lastUpdatedTimeIntervalSince1970 doubleValue]];
}
}
}
return nil;
}
- (BOOL)isAutoRefreshNeeded {
BOOL isAutoRefreshNeeded = NO;
if (_autoRefreshFromNetwork) {
isAutoRefreshNeeded = YES;
NSDate* lastUpdatedDate = [self lastUpdatedDate];
RKLogTrace(@"Last updated: %@", lastUpdatedDate);
if (lastUpdatedDate) {
RKLogTrace(@"-timeIntervalSinceNow=%f, autoRefreshRate=%f",
-[lastUpdatedDate timeIntervalSinceNow], _autoRefreshRate);
isAutoRefreshNeeded = (-[lastUpdatedDate timeIntervalSinceNow] > _autoRefreshRate);
}
}
return isAutoRefreshNeeded;
}
#pragma mark - RKRequestDelegate & RKObjectLoaderDelegate methods
- (void)requestDidStartLoad:(RKRequest*)request {
RKLogTrace(@"tableController %@ started loading.", self);
self.loading = YES;
}
- (void)requestDidCancelLoad:(RKRequest*)request {
RKLogTrace(@"tableController %@ cancelled loading.", self);
self.loading = NO;
if ([self.delegate respondsToSelector:@selector(tableControllerDidCancelLoad:)]) {
[self.delegate tableControllerDidCancelLoad:self];
}
}
- (void)requestDidTimeout:(RKRequest*)request {
RKLogTrace(@"tableController %@ timed out while loading.", self);
self.loading = NO;
}
- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {
RKLogTrace(@"tableController %@ finished loading.", self);
// Updated the lastUpdatedDate dictionary using the URL of the request
if (self.autoRefreshFromNetwork) {
NSAssert(_cache, @"Found a nil cache when trying to save our last loaded time");
NSMutableDictionary* lastUpdatedDates = [[_cache dictionaryForCacheKey:lastUpdatedDateDictionaryKey] mutableCopy];
if (lastUpdatedDates) {
[_cache invalidateEntry:lastUpdatedDateDictionaryKey];
} else {
lastUpdatedDates = [[NSMutableDictionary alloc] init];
}
NSNumber* timeIntervalSince1970 = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
RKLogTrace(@"Setting timeIntervalSince1970=%@ for URL %@", timeIntervalSince1970, [request.URL absoluteString]);
[lastUpdatedDates setObject:timeIntervalSince1970
forKey:[request.URL absoluteString]];
[_cache writeDictionary:lastUpdatedDates withCacheKey:lastUpdatedDateDictionaryKey];
[lastUpdatedDates release];
}
}
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
RKLogError(@"tableController %@ failed network load with error: %@", self, error);
self.error = error;
[self didFinishLoad];
}
- (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader {
if ([self.delegate respondsToSelector:@selector(tableController:didLoadTableWithObjectLoader:)]) {
[self.delegate tableController:self didLoadTableWithObjectLoader:objectLoader];
}
[self.objectLoader reset];
[self didFinishLoad];
}
- (void)didFinishLoad {
self.empty = [self isEmpty];
self.loading = [self.objectLoader isLoading]; // Mutate loading state after we have adjusted empty
self.loaded = YES;
// Setup offline image state based on current online/offline state
[self updateOfflineImageForOnlineState:[self isOnline]];
[self resetOverlayView];
if (self.delegate && [_delegate respondsToSelector:@selector(tableControllerDidFinishFinalLoad:)])
[_delegate performSelector:@selector(tableControllerDidFinishFinalLoad:)];
}
#pragma mark - Table Overlay Views
// Adds an overlay view above the table
- (void)addToOverlayView:(UIView *)view modally:(BOOL)modally {
if (! _tableOverlayView) {
CGRect overlayFrame = CGRectIsEmpty(self.overlayFrame) ? self.tableView.frame : self.overlayFrame;
_tableOverlayView = [[UIView alloc] initWithFrame:overlayFrame];
_tableOverlayView.autoresizesSubviews = YES;
_tableOverlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
NSInteger tableIndex = [_tableView.superview.subviews indexOfObject:_tableView];
if (tableIndex != NSNotFound) {
[_tableView.superview addSubview:_tableOverlayView];
}
}
// When modal, we enable user interaction to catch & discard events on the overlay and its subviews
_tableOverlayView.userInteractionEnabled = modally;
view.userInteractionEnabled = modally;
if (CGRectIsEmpty(view.frame)) {
view.frame = _tableOverlayView.bounds;
// Center it in the overlay
view.center = _tableOverlayView.center;
}
[_tableOverlayView addSubview:view];
}
- (void)resetOverlayView {
if (_stateOverlayImageView && _stateOverlayImageView.image == nil) {
[_stateOverlayImageView removeFromSuperview];
}
if (_tableOverlayView && _tableOverlayView.subviews.count == 0) {
[_tableOverlayView removeFromSuperview];
[_tableOverlayView release];
_tableOverlayView = nil;
}
}
- (void)addSubviewOverTableView:(UIView *)view {
NSInteger tableIndex = [_tableView.superview.subviews
indexOfObject:_tableView];
if (NSNotFound != tableIndex) {
[_tableView.superview addSubview:view];
}
}
- (BOOL)removeImageFromOverlay:(UIImage *)image {
if (image && _stateOverlayImageView.image == image) {
_stateOverlayImageView.image = nil;
return YES;
}
return NO;
}
- (void)showImageInOverlay:(UIImage *)image {
NSAssert(self.tableView, @"Cannot add an overlay image to a nil tableView");
if (! _stateOverlayImageView) {
_stateOverlayImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
_stateOverlayImageView.opaque = YES;
_stateOverlayImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
_stateOverlayImageView.contentMode = UIViewContentModeCenter;
}
_stateOverlayImageView.image = image;
[self addToOverlayView:_stateOverlayImageView modally:self.showsOverlayImagesModally];
}
- (void)removeImageOverlay {
_stateOverlayImageView.image = nil;
[_stateOverlayImageView removeFromSuperview];
[self resetOverlayView];
}
- (void)setImageForEmpty:(UIImage*)imageForEmpty {
[imageForEmpty retain];
BOOL imageRemoved = [self removeImageFromOverlay:_imageForEmpty];
[_imageForEmpty release];
_imageForEmpty = imageForEmpty;
if (imageRemoved) [self showImageInOverlay:_imageForEmpty];
}
- (void)setImageForError:(UIImage*)imageForError {
[imageForError retain];
BOOL imageRemoved = [self removeImageFromOverlay:_imageForError];
[_imageForError release];
_imageForError = imageForError;
if (imageRemoved) [self showImageInOverlay:_imageForError];
}
- (void)setImageForOffline:(UIImage*)imageForOffline {
[imageForOffline retain];
BOOL imageRemoved = [self removeImageFromOverlay:_imageForOffline];
[_imageForOffline release];
_imageForOffline = imageForOffline;
if (imageRemoved) [self showImageInOverlay:_imageForOffline];
}
- (void)setLoadingView:(UIView*)loadingView {
[loadingView retain];
BOOL viewRemoved = (_loadingView.superview != nil);
[_loadingView removeFromSuperview];
[self resetOverlayView];
[_loadingView release];
_loadingView = loadingView;
if (viewRemoved) [self addToOverlayView:_loadingView modally:NO];
}
#pragma mark - KVO & Model States
- (BOOL)isLoading {
return self.loading;
}
- (BOOL)isLoaded {
return self.loaded;
}
- (BOOL)isOnline {
return self.online;
}
- (BOOL)isError {
return _error != nil;
}
- (BOOL)isEmpty {
NSUInteger nonRowItemsCount = [_headerItems count] + [_footerItems count];
nonRowItemsCount += _emptyItem ? 1 : 0;
BOOL isEmpty = (self.rowCount - nonRowItemsCount) == 0;
RKLogTrace(@"Determined isEmpty = %@. self.rowCount = %d with %d nonRowItems in the table", isEmpty ? @"YES" : @"NO", self.rowCount, nonRowItemsCount);
return isEmpty;
}
- (void)isLoadingDidChangeTo:(BOOL)isLoading {
if (isLoading) {
// Remove any current state to allow drawing of the loading view
[self removeImageOverlay];
// Clear the error state
self.error = nil;
self.empty = NO;
if ([self.delegate respondsToSelector:@selector(tableControllerDidStartLoad:)]) {
[self.delegate tableControllerDidStartLoad:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidStartLoadNotification object:self];
if (self.loadingView) {
[self addToOverlayView:self.loadingView modally:NO];
}
} else {
if ([self.delegate respondsToSelector:@selector(tableControllerDidFinishLoad:)]) {
[self.delegate tableControllerDidFinishLoad:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidFinishLoadNotification object:self];
if (self.loadingView) {
[self.loadingView removeFromSuperview];
[self resetOverlayView];
}
[(EGORefreshTableHeaderView*)_pullToRefreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}
// We don't want any image overlays applied until loading is finished
_stateOverlayImageView.hidden = isLoading;
}
- (void)isLoadedDidChangeTo:(BOOL)isLoaded {
if (isLoaded) {
RKLogDebug(@"%@: is now loaded.", self);
} else {
RKLogDebug(@"%@: is NOT loaded.", self);
}
}
- (void)errorDidChangeTo:(BOOL)isError {
if (isError) {
if ([self.delegate respondsToSelector:@selector(tableController:didFailLoadWithError:)]) {
[self.delegate tableController:self didFailLoadWithError:self.error];
}
NSDictionary* userInfo = [NSDictionary dictionaryWithObject:self.error forKey:RKErrorNotificationErrorKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidLoadErrorNotification object:self userInfo:userInfo];
if (self.imageForError) {
[self showImageInOverlay:self.imageForError];
}
} else {
[self removeImageFromOverlay:self.imageForError];
}
}
- (void)isEmptyDidChangeTo:(BOOL)isEmpty {
if (isEmpty) {
// TODO: maybe this should be didLoadEmpty?
if ([self.delegate respondsToSelector:@selector(tableControllerDidBecomeEmpty:)]) {
[self.delegate tableControllerDidBecomeEmpty:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidLoadEmptyNotification object:self];
if (self.imageForEmpty) {
[self showImageInOverlay:self.imageForEmpty];
}
} else {
if (self.imageForEmpty) {
[self removeImageFromOverlay:self.imageForEmpty];
}
}
}
- (void)updateOfflineImageForOnlineState:(BOOL)isOnline {
if (isOnline) {
[self removeImageFromOverlay:self.imageForOffline];
} else {
if (self.imageForOffline) {
[self showImageInOverlay:self.imageForOffline];
}
}
}
- (void)isOnlineDidChangeTo:(BOOL)isOnline {
if (isOnline) {
// We just transitioned to online
if ([self.delegate respondsToSelector:@selector(tableControllerDidBecomeOnline:)]) {
[self.delegate tableControllerDidBecomeOnline:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidBecomeOnline object:self];
} else {
// We just transitioned to offline
if ([self.delegate respondsToSelector:@selector(tableControllerDidBecomeOffline:)]) {
[self.delegate tableControllerDidBecomeOffline:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidBecomeOffline object:self];
}
[self updateOfflineImageForOnlineState:isOnline];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {