/
RKManagedObjectRequestOperation.m
946 lines (829 loc) · 42.4 KB
/
RKManagedObjectRequestOperation.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
//
// RKManagedObjectRequestOperation.m
// RestKit
//
// Created by Blake Watters on 8/9/12.
// Copyright (c) 2012 RestKit. All rights reserved.
//
// 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.
//
#if __has_include("CoreData.h")
#if __has_include("RKManagedObjectCaching.h")
#import "RKManagedObjectRequestOperation.h"
#import "RKLog.h"
#import "RKHTTPUtilities.h"
#import "RKResponseMapperOperation.h"
#import "RKObjectRequestOperationSubclass.h"
#import "NSManagedObjectContext+RKAdditions.h"
#import "NSManagedObject+RKAdditions.h"
#import "RKObjectUtilities.h"
// Graph visitor
#import "RKResponseDescriptor.h"
#import "RKEntityMapping.h"
#import "RKDynamicMapping.h"
#import "RKRelationshipMapping.h"
// Set Logging Component
#undef RKLogComponent
#define RKLogComponent RKlcl_cRestKitNetworkCoreData
@interface RKEntityMappingEvent : NSObject
@property (nonatomic, copy) id rootKey;
@property (nonatomic, copy) NSString *keyPath;
@property (nonatomic, strong) RKEntityMapping *entityMapping;
+ (NSArray *)entityMappingEventsForMappingInfo:(NSDictionary *)mappingInfo;
+ (instancetype)eventWithRootKey:(id)rootKey keyPath:(NSString *)keyPath entityMapping:(RKEntityMapping *)entityMapping;
@end
@implementation RKEntityMappingEvent
+ (NSArray *)entityMappingEventsForMappingInfo:(NSDictionary *)mappingInfo
{
NSMutableArray *entityMappingEvents = [NSMutableArray array];
for (id rootKey in mappingInfo) {
NSArray *mappingInfoArray = mappingInfo[rootKey];
for (RKMappingInfo *mappingInfo in mappingInfoArray) {
[entityMappingEvents addObjectsFromArray:[self entityMappingEventsWithMappingInfo:mappingInfo rootKey:rootKey keyPath:nil]];
}
}
return entityMappingEvents;
}
+ (NSArray *)entityMappingEventsWithMappingInfo:(RKMappingInfo *)mappingInfo rootKey:(id)rootKey keyPath:(NSString *)keyPath
{
NSMutableArray *entityMappingEvents = [NSMutableArray array];
if ([mappingInfo.objectMapping isKindOfClass:[RKEntityMapping class]]) {
[entityMappingEvents addObject:[RKEntityMappingEvent eventWithRootKey:rootKey
keyPath:keyPath
entityMapping:(RKEntityMapping *)mappingInfo.objectMapping]];
}
for (NSString *destinationKeyPath in mappingInfo.relationshipMappingInfo) {
NSString *nestedKeyPath = keyPath ? [@[ keyPath, destinationKeyPath] componentsJoinedByString:@"."] : destinationKeyPath;
NSArray *arrayOfMappingInfoForRelationship = (mappingInfo.relationshipMappingInfo)[destinationKeyPath];
for (RKMappingInfo *mappingInfo in arrayOfMappingInfoForRelationship) {
[entityMappingEvents addObjectsFromArray:[self entityMappingEventsWithMappingInfo:mappingInfo rootKey:rootKey keyPath:nestedKeyPath]];
}
}
return entityMappingEvents;
}
+ (instancetype)eventWithRootKey:(id)rootKey keyPath:(NSString *)keyPath entityMapping:(RKEntityMapping *)entityMapping
{
RKEntityMappingEvent *event = [RKEntityMappingEvent new];
event.rootKey = rootKey;
event.keyPath = keyPath;
event.entityMapping = entityMapping;
return event;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p rootKey=%@ keyPath=%@ entityMapping=%@>",
[self class], self, self.rootKey, self.keyPath, self.entityMapping];
}
@end
/**
Returns the set of keys containing the outermost nesting keypath for all children.
For example, given a set containing: 'this', 'this.that', 'another.one.test', 'another.two.test', 'another.one.test.nested'
would return: 'this, 'another.one', 'another.two'
*/
NSSet *RKSetByRemovingSubkeypathsFromSet(NSSet *setOfKeyPaths);
NSSet *RKSetByRemovingSubkeypathsFromSet(NSSet *setOfKeyPaths)
{
return [setOfKeyPaths objectsPassingTest:^BOOL(NSString *keyPath, BOOL *stop) {
if ([keyPath isEqual:[NSNull null]]) return YES; // Special case the root key path
NSArray *keyPathComponents = [keyPath componentsSeparatedByString:@"."];
NSMutableSet *parentKeyPaths = [NSMutableSet set];
for (NSUInteger index = 0; index < [keyPathComponents count] - 1; index++) {
[parentKeyPaths addObject:[[keyPathComponents subarrayWithRange:NSMakeRange(0, index + 1)] componentsJoinedByString:@"."]];
}
for (NSString *parentKeyPath in parentKeyPaths) {
if ([setOfKeyPaths containsObject:parentKeyPath]) return NO;
}
return YES;
}];
}
// Precondition: Must be called from within the correct context
static NSManagedObject *RKRefetchManagedObjectInContext(NSManagedObject *managedObject, NSManagedObjectContext *managedObjectContext)
{
NSManagedObjectID *managedObjectID = [managedObject objectID];
if ([managedObjectID isTemporaryID]) {
RKLogWarning(@"Unable to refetch managed object %@: the object has a temporary managed object ID.", managedObject);
return nil;
}
NSError *error = nil;
NSManagedObject *refetchedObject = [managedObjectContext existingObjectWithID:managedObjectID error:&error];
if (! refetchedObject) {
RKLogWarning(@"Failed to refetch managed object with ID %@: %@", managedObjectID, error);
}
return refetchedObject;
}
static id RKRefetchedValueInManagedObjectContext(id value, NSManagedObjectContext *managedObjectContext)
{
if (! value) {
return value;
} else if ([value isKindOfClass:[NSArray class]]) {
NSMutableArray *newValue = [[NSMutableArray alloc] initWithCapacity:[value count]];
for (__strong id object in value) {
if ([object isKindOfClass:[NSManagedObject class]]) object = RKRefetchManagedObjectInContext(object, managedObjectContext);
if (object) [newValue addObject:object];
}
return newValue;
} else if ([value isKindOfClass:[NSSet class]]) {
NSMutableSet *newValue = [[NSMutableSet alloc] initWithCapacity:[value count]];
for (__strong id object in value) {
if ([object isKindOfClass:[NSManagedObject class]]) object = RKRefetchManagedObjectInContext(object, managedObjectContext);
if (object) [newValue addObject:object];
}
return newValue;
} else if ([value isKindOfClass:[NSOrderedSet class]]) {
NSMutableOrderedSet *newValue = [NSMutableOrderedSet orderedSet];
[(NSOrderedSet *)value enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
if ([object isKindOfClass:[NSManagedObject class]]) object = RKRefetchManagedObjectInContext(object, managedObjectContext);
if (object) [newValue setObject:object atIndex:index];
}];
return newValue;
} else if ([value isKindOfClass:[NSManagedObject class]]) {
return RKRefetchManagedObjectInContext(value, managedObjectContext);
}
return value;
}
/**
This is an NSProxy object that stands in for the mapping result and provides support for refetching the results on demand. This enables us to defer the refetching until someone accesses the results directly. For managed object request operations that do not use the mapping result (such as those used in conjunction with a NSFetchedResultsController), the refetching will be skipped entirely.
*/
@interface RKRefetchingMappingResult : NSProxy
- (instancetype)initWithMappingResult:(RKMappingResult *)mappingResult
managedObjectContext:(NSManagedObjectContext *)managedObjectContext
mappingInfo:(NSDictionary *)mappingInfo;
@end
@interface RKRefetchingMappingResult ()
@property (nonatomic, strong) RKMappingResult *mappingResult;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSDictionary *mappingInfo;
@property (nonatomic, assign) BOOL refetched;
@end
@implementation RKRefetchingMappingResult
+ (NSString *)description
{
return [[super description] stringByAppendingString:@"_RKRefetchingMappingResult"];
}
/**
Add explicit ordering of deallocations to fight `cxx_destruct` crashes
*/
- (void)dealloc
{
_mappingResult = nil;
_mappingInfo = nil;
_managedObjectContext = nil;
}
- (instancetype)initWithMappingResult:(RKMappingResult *)mappingResult
managedObjectContext:(NSManagedObjectContext *)managedObjectContext
mappingInfo:(NSDictionary *)mappingInfo;
{
self.mappingResult = mappingResult;
self.managedObjectContext = managedObjectContext;
self.mappingInfo = mappingInfo;
return self;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
return [self.mappingResult methodSignatureForSelector:selector];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
if (! self.refetched) {
self.mappingResult = [self refetchedMappingResult];
self.refetched = YES;
}
[invocation invokeWithTarget:self.mappingResult];
}
- (NSString *)description
{
return [self.mappingResult description];
}
- (NSUInteger)count
{
return [self.mappingResult count];
}
- (RKMappingResult *)refetchedMappingResult
{
NSAssert(!self.refetched, @"Mapping result should only be refetched once");
if (! [self.mappingResult count]) return self.mappingResult;
NSMutableDictionary *newDictionary = [self.mappingResult.dictionary mutableCopy];
[self.managedObjectContext performBlockAndWait:^{
NSArray *entityMappingEvents = [RKEntityMappingEvent entityMappingEventsForMappingInfo:self.mappingInfo];
NSSet *rootKeys = [NSSet setWithArray:[entityMappingEvents valueForKey:@"rootKey"]];
for (id rootKey in rootKeys) {
NSArray *eventsForRootKey = [entityMappingEvents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"rootKey = %@", rootKey]];
NSSet *keyPaths = [NSSet setWithArray:[eventsForRootKey valueForKey:@"keyPath"]];
// If keyPaths contains null, then the root object is a managed object and we only need to refetch it
NSSet *nonNestedKeyPaths = ([keyPaths containsObject:[NSNull null]]) ? [NSSet setWithObject:[NSNull null]] : RKSetByRemovingSubkeypathsFromSet(keyPaths);
NSDictionary *mappingResultsAtRootKey = newDictionary[rootKey];
for (NSString *keyPath in nonNestedKeyPaths) {
id value = nil;
if ([keyPath isEqual:[NSNull null]]) {
value = RKRefetchedValueInManagedObjectContext(mappingResultsAtRootKey, self.managedObjectContext);
if (value) {
newDictionary[rootKey] = value;
}
// else there's no object on the correct context
else {
// ensure newDictionary doesn't have an object on an incorrect context
[newDictionary removeObjectForKey:rootKey];
}
} else {
NSMutableArray *keyPathComponents = [[keyPath componentsSeparatedByString:@"."] mutableCopy];
NSString *destinationKey = [keyPathComponents lastObject];
[keyPathComponents removeLastObject];
id sourceObject = [keyPathComponents count] ? [mappingResultsAtRootKey valueForKeyPath:[keyPathComponents componentsJoinedByString:@"."]] : mappingResultsAtRootKey;
[self refetchSourceObject:sourceObject atDestinationKey:destinationKey];
}
}
}
}];
return [[RKMappingResult alloc] initWithDictionary:newDictionary];
}
- (void) refetchSourceObject:(id) sourceObject atDestinationKey:(NSString *)destinationKey {
if (RKObjectIsCollection(sourceObject)) {
// This is a to-many relationship, we want to refetch each item at the keyPath
for (id nestedObject in sourceObject) {
[self refetchSourceObject:nestedObject atDestinationKey:destinationKey];
}
} else {
// NOTE: If this collection was mapped with a dynamic mapping then each instance may not respond to the key
if ([sourceObject respondsToSelector:NSSelectorFromString(destinationKey)]) {
id valueToRefetch = [sourceObject valueForKey:destinationKey];
[sourceObject setValue:RKRefetchedValueInManagedObjectContext(valueToRefetch, self.managedObjectContext) forKey:destinationKey];
}
}
}
@end
NSArray *RKArrayOfFetchRequestFromBlocksWithURL(NSArray *fetchRequestBlocks, NSURL *URL)
{
NSMutableArray *fetchRequests = [NSMutableArray array];
NSFetchRequest *fetchRequest = nil;
for (RKFetchRequestBlock block in [fetchRequestBlocks reverseObjectEnumerator]) {
fetchRequest = block(URL);
if (fetchRequest) [fetchRequests addObject:fetchRequest];
}
return fetchRequests;
}
static NSSet *RKFlattenCollectionToSet(id collection)
{
NSMutableSet *mutableSet = [NSMutableSet set];
if ([collection conformsToProtocol:@protocol(NSFastEnumeration)]) {
for (id nestedObject in collection) {
if ([nestedObject conformsToProtocol:@protocol(NSFastEnumeration)]) {
if ([nestedObject isKindOfClass:[NSArray class]]) {
[mutableSet unionSet:RKFlattenCollectionToSet([NSSet setWithArray:nestedObject])];
} else if ([nestedObject isKindOfClass:[NSSet class]]) {
[mutableSet unionSet:RKFlattenCollectionToSet(nestedObject)];
} else if ([nestedObject isKindOfClass:[NSOrderedSet class]]) {
[mutableSet unionSet:RKFlattenCollectionToSet([(NSOrderedSet *)nestedObject set])];
}
} else {
[mutableSet addObject:nestedObject];
}
}
} else if (collection) {
[mutableSet addObject:collection];
}
return mutableSet;
}
static NSURL *RKRelativeURLFromURLAndResponseDescriptors(NSURL *URL, NSArray *responseDescriptors)
{
NSCParameterAssert(URL);
NSCParameterAssert(responseDescriptors);
NSArray *baseURLs = [responseDescriptors valueForKeyPath:@"@distinctUnionOfObjects.baseURL"];
if ([baseURLs count] == 1) {
NSURL *baseURL = baseURLs[0];
NSString *pathAndQueryString = RKPathAndQueryStringFromURLRelativeToURL(URL, baseURL);
URL = [NSURL URLWithString:pathAndQueryString relativeToURL:baseURL];
}
return URL;
}
static void RKGatherManagedObjectsFromObjectWithRelationshipMapping(id object, RKRelationshipMapping *relationshipMapping, NSMutableSet *managedObjects)
{
NSSet *relationshipValue = RKFlattenCollectionToSet([object valueForKeyPath:relationshipMapping.destinationKeyPath]);
for (id relatedObject in relationshipValue) {
if ([managedObjects containsObject:relatedObject]) continue;
if ([relatedObject isKindOfClass:[NSManagedObject class]]) [managedObjects addObject:relatedObject];
if ([relationshipMapping.mapping isKindOfClass:[RKObjectMapping class]]) {
for (RKRelationshipMapping *childRelationshipMapping in [(RKObjectMapping *)relationshipMapping.mapping relationshipMappings]) {
RKGatherManagedObjectsFromObjectWithRelationshipMapping(relatedObject, childRelationshipMapping, managedObjects);
}
} else if ([relationshipMapping.mapping isKindOfClass:[RKDynamicMapping class]]) {
for (RKObjectMapping *objectMapping in [(RKDynamicMapping *)relationshipMapping.mapping objectMappings]) {
@try {
for (RKRelationshipMapping *childRelationshipMapping in objectMapping.relationshipMappings) {
RKGatherManagedObjectsFromObjectWithRelationshipMapping(relatedObject, childRelationshipMapping, managedObjects);
}
}
@catch (NSException *exception) {
continue;
}
}
}
}
}
static NSSet *RKManagedObjectsFromObjectWithMappingInfo(id object, RKMappingInfo *mappingInfo)
{
NSMutableSet *managedObjects = [NSMutableSet set];
if ([mappingInfo.objectMapping isKindOfClass:[RKEntityMapping class]]) {
[managedObjects unionSet:RKFlattenCollectionToSet(object)];
}
if ([[mappingInfo propertyMappings] count] == 0) {
// This object was matched, but no changes were made. Gather all related objects
for (RKRelationshipMapping *relationshipMapping in [mappingInfo.objectMapping relationshipMappings]) {
RKGatherManagedObjectsFromObjectWithRelationshipMapping(object, relationshipMapping, managedObjects);
}
} else {
for (NSString *destinationKeyPath in mappingInfo.relationshipMappingInfo) {
id relationshipValue = nil;
// Objects in collection may have different types, so destination keypath may be not applicable to each of them
if([object conformsToProtocol:@protocol(NSFastEnumeration)]) {
NSMutableSet* results = [NSMutableSet set];
for (id item in object) {
id value = nil;
@try {
value = [item valueForKeyPath:destinationKeyPath];
} @catch(NSException*) {
continue;
}
if (value != nil) {
[results addObject:value];
}
}
relationshipValue = results;
} else {
relationshipValue = [object valueForKeyPath:destinationKeyPath];
}
NSArray *mappingInfos = (mappingInfo.relationshipMappingInfo)[destinationKeyPath];
for (RKMappingInfo *relationshipMappingInfo in mappingInfos) {
NSUInteger index = [mappingInfos indexOfObject:relationshipMappingInfo];
id mappedObjectAtIndex = ([relationshipValue respondsToSelector:@selector(objectAtIndex:)]) ? relationshipValue[index] : relationshipValue;
[managedObjects unionSet:RKFlattenCollectionToSet(RKManagedObjectsFromObjectWithMappingInfo(mappedObjectAtIndex, relationshipMappingInfo))];
}
}
}
return ([managedObjects count]) ? managedObjects : nil;
}
static NSSet *RKManagedObjectsFromMappingResultWithMappingInfo(RKMappingResult *mappingResult, NSDictionary *mappingInfo)
{
NSMutableSet *managedObjectsInMappingResult = nil;
NSDictionary *mappingResultDictionary = [mappingResult dictionary];
for (id rootKey in mappingInfo) {
NSArray *mappingInfoArray = mappingInfo[rootKey];
id objectsAtRoot = mappingResultDictionary[rootKey];
for (RKMappingInfo *mappingInfo in mappingInfoArray) {
NSUInteger index = [mappingInfoArray indexOfObject:mappingInfo];
id mappedObjectAtIndex = ([objectsAtRoot respondsToSelector:@selector(objectAtIndex:)]) ? objectsAtRoot[index] : objectsAtRoot;
NSSet *managedObjects = RKManagedObjectsFromObjectWithMappingInfo(mappedObjectAtIndex, mappingInfo);
if (managedObjects) {
if (! managedObjectsInMappingResult) managedObjectsInMappingResult = [NSMutableSet set];
[managedObjectsInMappingResult unionSet:managedObjects];
}
}
};
return managedObjectsInMappingResult;
}
// Defined in RKObjectManager.h
BOOL RKDoesArrayOfResponseDescriptorsContainOnlyEntityMappings(NSArray *responseDescriptors);
@interface RKObjectRequestOperation ()
@property (nonatomic, strong, readwrite) NSError *error;
@property (nonatomic, strong, readwrite) RKMappingResult *mappingResult;
@end
@interface RKManagedObjectRequestOperation ()
// Core Data specific
@property (nonatomic, strong) NSManagedObjectContext *privateContext;
@property (nonatomic, copy) NSManagedObjectID *targetObjectID;
@property (nonatomic, strong) RKManagedObjectResponseMapperOperation *responseMapperOperation;
@property (nonatomic, copy) id (^willMapDeserializedResponseBlock)(id deserializedResponseBody);
@property (nonatomic, strong) NSDictionary *mappingInfo;
@property (nonatomic, strong) NSCachedURLResponse *cachedResponse;
@property (nonatomic, readonly) BOOL canSkipMapping;
@property (nonatomic, assign) BOOL hasMemoizedCanSkipMapping;
@property (nonatomic, copy) void (^willSaveMappingContextBlock)(NSManagedObjectContext *mappingContext);
@end
@implementation RKManagedObjectRequestOperation
@dynamic willMapDeserializedResponseBlock;
@synthesize canSkipMapping = _canSkipMapping;
// Designated initializer
- (instancetype)initWithHTTPRequestOperation:(RKHTTPRequestOperation *)requestOperation responseDescriptors:(NSArray *)responseDescriptors
{
self = [super initWithHTTPRequestOperation:requestOperation responseDescriptors:responseDescriptors];
if (self) {
self.savesToPersistentStore = YES;
self.deletesOrphanedObjects = YES;
self.cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:requestOperation.request];
}
return self;
}
/**
NOTE: This dealloc implementation attempts to avoid crashes coming from Core Data due to the ordering of deallocations under ARC. If the MOC is deallocated before its managed objects, it can trigger a crash. We dispose of the mapping result and reset the private context to avoid this situation. The crash manifests itself in `cxx_destruct`
[sbw - 2/25/2013]
*/
- (void)dealloc
{
_mappingResult = nil;
_responseMapperOperation = nil;
_privateContext = nil;
}
- (void)setTargetObject:(id)targetObject
{
[super setTargetObject:targetObject];
if ([targetObject isKindOfClass:[NSManagedObject class]]) {
if ([[targetObject objectID] isTemporaryID]) {
[[targetObject managedObjectContext] performBlockAndWait:^{
NSError *error = nil;
BOOL success = [[targetObject managedObjectContext] obtainPermanentIDsForObjects:@[ targetObject ] error:&error];
if (! success) RKLogWarning(@"Failed to obtain permanent objectID for targetObject: %@ (%ld)", [error localizedDescription], (long) error.code);
}];
}
self.targetObjectID = [targetObject objectID];
} else {
self.targetObjectID = nil;
}
}
- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
_managedObjectContext = managedObjectContext;
if (managedObjectContext) {
[managedObjectContext performBlockAndWait:^{
if ([managedObjectContext hasChanges]) {
if ([managedObjectContext.insertedObjects count] && [self.managedObjectCache respondsToSelector:@selector(didCreateObject:)]) {
for (NSManagedObject *managedObject in managedObjectContext.insertedObjects) {
[self.managedObjectCache didCreateObject:managedObject];
}
}
if ([managedObjectContext.updatedObjects count] && [self.managedObjectCache respondsToSelector:@selector(didFetchObject:)]) {
for (NSManagedObject *managedObject in managedObjectContext.updatedObjects) {
[self.managedObjectCache didFetchObject:managedObject];
}
}
if ([managedObjectContext.deletedObjects count] && [self.managedObjectCache respondsToSelector:@selector(didDeleteObject:)]) {
for (NSManagedObject *managedObject in managedObjectContext.deletedObjects) {
[self.managedObjectCache didDeleteObject:managedObject];
}
}
}
}];
// Create a private context
NSManagedObjectContext *privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[privateContext setParentContext:managedObjectContext];
[privateContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
self.privateContext = privateContext;
} else {
self.privateContext = nil;
}
}
#pragma mark - RKObjectRequestOperation Overrides
- (void)cancel
{
[super cancel];
[self.responseMapperOperation cancel];
}
// RKResponseHasBeenMappedCacheUserInfoKey is stored by RKObjectRequestOperation
- (BOOL)canSkipMapping
{
BOOL (^shouldSkipMapping)(void) = ^{
// Is the request cacheable
if (!self.cachedResponse) return NO;
if (!self.managedObjectCache) return NO;
NSURLRequest *request = self.HTTPRequestOperation.request;
if (! [[request HTTPMethod] isEqualToString:@"GET"] && ! [[request HTTPMethod] isEqualToString:@"HEAD"]) return NO;
NSHTTPURLResponse *response = (NSHTTPURLResponse *)self.HTTPRequestOperation.response;
if (! [RKCacheableStatusCodes() containsIndex:response.statusCode]) return NO;
// Check if all the response descriptors are backed by Core Data
NSMutableArray *matchingResponseDescriptors = [NSMutableArray array];
for (RKResponseDescriptor *responseDescriptor in self.responseDescriptors) {
if ([responseDescriptor matchesResponse:response]) [matchingResponseDescriptors addObject:responseDescriptor];
}
if (! RKDoesArrayOfResponseDescriptorsContainOnlyEntityMappings(matchingResponseDescriptors)) return NO;
// Check for a change in the Etag
NSString *cachedEtag = [(NSHTTPURLResponse *)[self.cachedResponse response] allHeaderFields][@"ETag"];
NSString *responseEtag = [response allHeaderFields][@"ETag"];
if (!(cachedEtag && responseEtag && [cachedEtag isEqualToString:responseEtag])) return NO;
// Response data has changed
NSData *responseData = self.HTTPRequestOperation.responseData;
if (! [responseData isEqualToData:[self.cachedResponse data]]) return NO;
// Check that we have mapped this response previously
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
return [(cachedResponse.userInfo)[RKResponseHasBeenMappedCacheUserInfoKey] boolValue];
};
if (! self.hasMemoizedCanSkipMapping) {
_canSkipMapping = shouldSkipMapping();
self.hasMemoizedCanSkipMapping = YES;
}
return _canSkipMapping;
}
- (void)performMappingOnResponseWithCompletionBlock:(void(^)(RKMappingResult *mappingResult, NSError *error))completionBlock
{
NSArray *fetchRequests = [self fetchRequestsMatchingResponseURL];
if ([fetchRequests count] && [self canSkipMapping]) {
RKLogDebug(@"Managed object mapping requested for cached response which was previously mapped: skipping...");
NSMutableArray *managedObjects = [NSMutableArray array];
[self.privateContext performBlockAndWait:^{
NSError *error = nil;
for (NSFetchRequest *fetchRequest in fetchRequests) {
NSArray *fetchedObjects = [self.privateContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects) {
[managedObjects addObjectsFromArray:fetchedObjects];
} else {
RKLogError(@"Failed to execute fetch request %@: %@", fetchRequest, error);
}
}
}];
RKMappingResult *mappingResult = [[RKMappingResult alloc] initWithDictionary:@{ [NSNull null]: managedObjects }];
completionBlock(mappingResult, nil);
return;
}
self.responseMapperOperation = [[RKManagedObjectResponseMapperOperation alloc] initWithRequest:self.HTTPRequestOperation.request
response:self.HTTPRequestOperation.response
data:self.HTTPRequestOperation.responseData
responseDescriptors:self.responseDescriptors];
self.responseMapperOperation.mapperDelegate = self;
self.responseMapperOperation.mappingMetadata = self.mappingMetadata;
self.responseMapperOperation.targetObject = self.targetObject;
self.responseMapperOperation.targetObjectID = self.targetObjectID;
self.responseMapperOperation.managedObjectContext = self.privateContext;
self.responseMapperOperation.managedObjectCache = self.managedObjectCache;
[self.responseMapperOperation setWillMapDeserializedResponseBlock:self.willMapDeserializedResponseBlock];
[self.responseMapperOperation setQueuePriority:[self queuePriority]];
__weak __typeof(self)weakSelf = self;
[self.responseMapperOperation setDidFinishMappingBlock:^(RKMappingResult *mappingResult, NSError *responseMappingError) {
if ([weakSelf isCancelled]) return completionBlock(mappingResult, responseMappingError);
BOOL success;
NSError *error = nil;
// Handle any cleanup
if (weakSelf.targetObjectID
&& NSLocationInRange(weakSelf.HTTPRequestOperation.response.statusCode, RKStatusCodeRangeForClass(RKStatusCodeClassSuccessful))
&& [[[weakSelf.HTTPRequestOperation.request HTTPMethod] uppercaseString] isEqualToString:@"DELETE"]) {
success = [weakSelf deleteTargetObject:&error];
if (! success || [weakSelf isCancelled]) {
return completionBlock(nil, error);
}
}
if (!responseMappingError) {
success = [weakSelf deleteLocalObjectsMissingFromMappingResult:mappingResult error:&error];
if (! success || [weakSelf isCancelled]) {
return completionBlock(nil, error);
}
// Persist our mapped objects
success = [weakSelf obtainPermanentObjectIDsForInsertedObjects:&error];
if (! success || [weakSelf isCancelled]) {
return completionBlock(nil, error);
}
success = [weakSelf saveContext:&error];
if (! success || [weakSelf isCancelled]) {
return completionBlock(nil, error);
}
}
// Refetch all managed objects nested at key paths within the results dictionary before returning
if (mappingResult) {
RKRefetchingMappingResult *refetchingMappingResult = [[RKRefetchingMappingResult alloc] initWithMappingResult:mappingResult
managedObjectContext:weakSelf.managedObjectContext
mappingInfo:weakSelf.mappingInfo];
return completionBlock((RKMappingResult *)refetchingMappingResult, nil);
}
completionBlock(nil, responseMappingError);
}];
[[RKObjectRequestOperation responseMappingQueue] addOperation:self.responseMapperOperation];
}
- (BOOL)deleteTargetObject:(NSError **)error
{
__block BOOL _blockSuccess = YES;
if (self.targetObjectID) {
// 2xx/404/410 DELETE request, proceed with deletion from the MOC
__block NSError *_blockError = nil;
[self.privateContext performBlockAndWait:^{
NSManagedObject *backgroundThreadObject = [self.privateContext existingObjectWithID:self.targetObjectID error:&_blockError];
if (backgroundThreadObject) {
RKLogInfo(@"Deleting local object %@ due to `DELETE` request", backgroundThreadObject);
[self.privateContext deleteObject:backgroundThreadObject];
} else {
RKLogWarning(@"Unable to delete object sent with `DELETE` request: Failed to retrieve object with objectID %@", self.targetObjectID);
RKLogCoreDataError(_blockError);
_blockSuccess = NO;
*error = _blockError;
}
}];
}
return _blockSuccess;
}
- (NSSet *)localObjectsFromFetchRequests:(NSArray *)fetchRequests matchingRequestURL:(NSError **)error
{
NSMutableSet *localObjects = [NSMutableSet set];
__block NSError *_blockError;
__block NSArray *_blockObjects;
for (NSFetchRequest *fetchRequest in fetchRequests) {
[self.privateContext performBlockAndWait:^{
_blockObjects = [self.privateContext executeFetchRequest:fetchRequest error:&_blockError];
}];
if (_blockObjects == nil) {
if (error) *error = _blockError;
return nil;
}
RKLogTrace(@"Fetched local objects matching URL with fetch request '%@': %@", fetchRequest, _blockObjects);
[localObjects addObjectsFromArray:_blockObjects];
}
return localObjects;
}
- (NSArray *)fetchRequestsMatchingResponseURL
{
// Pass the fetch request blocks a relative `NSURL` object if possible
NSMutableArray *fetchRequests = [NSMutableArray array];
NSURL *URL = RKRelativeURLFromURLAndResponseDescriptors(self.HTTPRequestOperation.response.URL, self.responseDescriptors);
for (RKFetchRequestBlock fetchRequestBlock in [self.fetchRequestBlocks reverseObjectEnumerator]) {
NSFetchRequest *fetchRequest = fetchRequestBlock(URL);
if (fetchRequest) {
// Workaround for iOS 5 -- The log statement crashes if the entity is not assigned before logging
[fetchRequest setEntity:[[[self.privateContext persistentStoreCoordinator] managedObjectModel] entitiesByName][[fetchRequest entityName]]];
RKLogDebug(@"Found fetch request matching URL '%@': %@", URL, fetchRequest);
[fetchRequests addObject:fetchRequest];
}
}
return fetchRequests;
}
- (BOOL)deleteLocalObjectsMissingFromMappingResult:(RKMappingResult *)mappingResult error:(NSError **)error
{
if (! self.deletesOrphanedObjects) {
RKLogDebug(@"Skipping deletion of orphaned objects: disabled as deletesOrphanedObjects=NO");
return YES;
}
if (! [[self.HTTPRequestOperation.request.HTTPMethod uppercaseString] isEqualToString:@"GET"]) {
RKLogDebug(@"Skipping deletion of orphaned objects: only performed for GET requests.");
return YES;
}
if ([self canSkipMapping]) {
RKLogDebug(@"Skipping deletion of orphaned objects: 304 (Not Modified) status code encountered");
return YES;
}
// Determine if there are any fetch request blocks to use for orphaned object cleanup
NSArray *fetchRequests = [self fetchRequestsMatchingResponseURL];
if (! [fetchRequests count]) return YES;
// Proceed with cleanup
__block NSSet *managedObjectsInMappingResult;
[self.privateContext performBlockAndWait:^{
managedObjectsInMappingResult = RKManagedObjectsFromMappingResultWithMappingInfo(mappingResult, self.mappingInfo) ?: [NSSet set];
}];
NSSet *localObjects = [self localObjectsFromFetchRequests:fetchRequests matchingRequestURL:error];
if (! localObjects) {
RKLogError(@"Failed when attempting to fetch local candidate objects for orphan cleanup: %@", error ? *error : nil);
return NO;
}
RKLogDebug(@"Checking mappings result of %ld objects for %ld potentially orphaned local objects...", (long) [managedObjectsInMappingResult count], (long) [localObjects count]);
NSMutableSet *orphanedObjects = [localObjects mutableCopy];
[orphanedObjects minusSet:managedObjectsInMappingResult];
RKLogDebug(@"Deleting %lu orphaned objects found in local database, but missing from mapping result", (unsigned long) [orphanedObjects count]);
if ([orphanedObjects count]) {
[self.privateContext performBlockAndWait:^{
for (NSManagedObject *orphanedObject in orphanedObjects) {
[self.privateContext deleteObject:orphanedObject];
}
}];
}
return YES;
}
/**
NOTE: This is more or less a direct port of the functionality provided by `[NSManagedObjectContext saveToPersistentStore:]` in the `RKAdditions` category. We have duplicated the logic here to add in support for checking if the operation has been cancelled since we began cascading up the MOC chain. Because each `performBlockAndWait:` invocation essentially jumps threads and is subject to the availability of the context, it is very possible for the operation to be cancelled during this part of the operation's lifecycle.
*/
- (BOOL)saveContextToPersistentStore:(NSManagedObjectContext *)contextToSave failedContext:(NSManagedObjectContext **)failedContext error:(NSError **)error
{
__block NSError *localError = nil;
while (contextToSave) {
__block BOOL success;
[contextToSave performBlockAndWait:^{
if (! [self isCancelled]) {
success = [contextToSave save:&localError];
if (! success && localError == nil) RKLogWarning(@"Saving of managed object context failed, but a `nil` value for the `error` argument was returned. This typically indicates an invalid implementation of a key-value validation method exists within your model. This violation of the API contract may result in the save operation being mis-interpretted by callers that rely on the availability of the error.");
} else {
// We have been cancelled while the save is in progress -- bail
success = NO;
}
}];
if (! success) {
if (error) *error = localError;
*failedContext = contextToSave;
return NO;
}
if (! contextToSave.parentContext && contextToSave.persistentStoreCoordinator == nil) {
RKLogWarning(@"Reached the end of the chain of nested managed object contexts without encountering a persistent store coordinator. Objects are not fully persisted.");
*failedContext = contextToSave;
return NO;
}
contextToSave = contextToSave.parentContext;
}
return YES;
}
- (BOOL)saveContext:(NSManagedObjectContext *)context error:(NSError **)error
{
__block BOOL success = YES;
__block NSError *localError = nil;
__block NSManagedObjectContext *failedContext = nil;
if (self.savesToPersistentStore) {
success = [self saveContextToPersistentStore:context failedContext:&failedContext error:&localError];
} else {
[context performBlockAndWait:^{
success = ([self isCancelled]) ? NO : [context save:&localError];
if (!success) {
failedContext = context;
}
}];
}
if (success) {
if ([self.targetObject isKindOfClass:[NSManagedObject class]]) {
[self.managedObjectContext performBlock:^{
RKLogDebug(@"Refreshing mapped target object %@ in context %@", self.targetObject, self.managedObjectContext);
if (! [self isCancelled]) [self.managedObjectContext refreshObject:self.targetObject mergeChanges:YES];
}];
}
} else {
if (error) *error = localError;
// Logging the error requires calling -[NSManagedObject description] which
// can only be done on the context's queue
[failedContext performBlock:^{
RKLogError(@"Failed saving managed object context %@ %@: %@", (self.savesToPersistentStore ? @"to the persistent store" : @""), context, localError);
RKLogCoreDataError(localError);
}];
}
return success;
}
- (BOOL)saveContext:(NSError **)error
{
if (self.willSaveMappingContextBlock) {
self.mappingResult = _responseMapperOperation.mappingResult;
[self.privateContext performBlockAndWait:^{
self.willSaveMappingContextBlock(self.privateContext);
}];
}
__block BOOL hasChanges;
[self.privateContext performBlockAndWait:^{
hasChanges = [self.privateContext hasChanges];
}];
if (hasChanges) {
return [self saveContext:self.privateContext error:error];
} else if ([self.targetObject isKindOfClass:[NSManagedObject class]]) {
NSManagedObjectContext *context = [(NSManagedObject *)self.targetObject managedObjectContext];
__block BOOL isNew = NO;
[context performBlockAndWait:^{
isNew = [(NSManagedObject *)self.targetObject isNew];
}];
// Object was like POST'd in an unsaved state and we wish to persist
if (isNew) [self saveContext:context error:error];
}
return YES;
}
- (BOOL)obtainPermanentObjectIDsForInsertedObjects:(NSError **)error
{
__block BOOL _blockSuccess = YES;
__block NSError *localError = nil;
[self.privateContext performBlockAndWait:^{
NSArray *insertedObjects = [[self.privateContext insertedObjects] allObjects];
RKLogDebug(@"Obtaining permanent ID's for %ld managed objects", (unsigned long) [insertedObjects count]);
_blockSuccess = [self.privateContext obtainPermanentIDsForObjects:insertedObjects error:&localError];
}];
if (!_blockSuccess && error) *error = localError;
return _blockSuccess;;
}
- (void)mapperDidFinishMapping:(RKMapperOperation *)mapper
{
self.mappingInfo = mapper.mappingInfo;
}
- (void)willFinish
{
NSMutableIndexSet *deleteableStatusCodes = [NSMutableIndexSet indexSet];
[deleteableStatusCodes addIndex:404]; // Not Found
[deleteableStatusCodes addIndex:410]; // Gone
if (self.error && self.targetObjectID
&& [[[self.HTTPRequestOperation.request HTTPMethod] uppercaseString] isEqualToString:@"DELETE"]
&& [deleteableStatusCodes containsIndex:self.HTTPRequestOperation.response.statusCode]) {
NSError *error = nil;
if (! [self deleteTargetObject:&error]) {
RKLogWarning(@"Secondary error encountered while attempting to delete target object in response to 404 (Not Found) or 410 (Gone) status code: %@", error);
self.error = error;
} else {
if (! [self saveContext:&error]) {
} else {
// All good, clear any errors
self.error = nil;
}
}
}
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
RKManagedObjectRequestOperation *operation = (RKManagedObjectRequestOperation *)[super copyWithZone:zone];
operation.managedObjectContext = self.managedObjectContext;
operation.managedObjectCache = self.managedObjectCache;
operation.fetchRequestBlocks = self.fetchRequestBlocks;
operation.deletesOrphanedObjects = self.deletesOrphanedObjects;
operation.savesToPersistentStore = self.savesToPersistentStore;
return operation;
}
@end
#endif
#endif