/
RKManagedObjectRequestOperation.m
694 lines (603 loc) · 31.3 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
//
// 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.
//
#import "RKManagedObjectRequestOperation.h"
#import "RKLog.h"
#import "RKHTTPUtilities.h"
#import "RKResponseMapperOperation.h"
#import "RKRequestOperationSubclass.h"
#import "NSManagedObjectContext+RKAdditions.h"
// Graph visitor
#import "RKResponseDescriptor.h"
#import "RKEntityMapping.h"
#import "RKDynamicMapping.h"
#import "RKRelationshipMapping.h"
// Set Logging Component
#undef RKLogComponent
#define RKLogComponent RKlcl_cRestKitCoreData
@interface RKMappingGraphVisitation : NSObject
@property (nonatomic, strong) id rootKey; // Will be [NSNull null] or a string value
@property (nonatomic, strong) NSString *keyPath;
@property (nonatomic, assign, getter = isCyclic) BOOL cyclic;
@property (nonatomic, strong) RKMapping *mapping;
@end
@implementation RKMappingGraphVisitation
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p rootKey=%@ keyPath=%@ isCylic=%@ mapping=%@>",
[self class], self, self.rootKey, self.keyPath, self.isCyclic ? @"YES" : @"NO", self.mapping];
}
@end
/**
This class implements Tarjan's algorithm to efficiently visit all nodes within the mapping graph and detect cycles in the graph.
For more details on the algorithm, refer to the Wikipedia page: http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
The following reference implementations were used when building out an Objective-C implementation:
1. http://algowiki.net/wiki/index.php?title=Tarjan%27s_algorithm
1. http://www.logarithmic.net/pfh-files/blog/01208083168/sort.py
*/
@interface RKNestedManagedObjectKeyPathMappingGraphVisitor : NSObject
@property (nonatomic, readonly, strong) NSMutableArray *visitations;
- (id)initWithResponseDescriptors:(NSArray *)responseDescriptors;
@end
@interface RKNestedManagedObjectKeyPathMappingGraphVisitor ()
@property (nonatomic, strong) NSMutableArray *visitationStack;
@property (nonatomic, strong) NSMutableDictionary *lowValues;
@property (nonatomic, strong) NSNumber *numberOfDecriptors;
@property (nonatomic, strong, readwrite) NSMutableArray *visitations;
@end
@implementation RKNestedManagedObjectKeyPathMappingGraphVisitor
- (id)initWithResponseDescriptors:(NSArray *)responseDescriptors
{
self = [self init];
if (self) {
self.numberOfDecriptors = @([responseDescriptors count]);
self.visitationStack = [NSMutableArray array];
self.lowValues = [NSMutableDictionary dictionary];
self.visitations = [NSMutableArray array];
for (RKResponseDescriptor *responseDescriptor in responseDescriptors) {
[self.visitationStack removeAllObjects];
[self.lowValues removeAllObjects];
[self visitMapping:responseDescriptor.mapping atKeyPath:responseDescriptor.keyPath];
}
}
return self;
}
- (RKMappingGraphVisitation *)visitationForMapping:(RKMapping *)mapping atKeyPath:(NSString *)keyPath
{
RKMappingGraphVisitation *visitation = [RKMappingGraphVisitation new];
visitation.mapping = mapping;
if ([self.visitationStack count] == 0) {
// If we are the first item in the stack, we are visiting the rootKey
visitation.rootKey = keyPath ?: [NSNull null];
} else {
// Take the root key from the visitation stack
visitation.rootKey = [[self.visitationStack objectAtIndex:0] rootKey];
visitation.keyPath = keyPath;
}
return visitation;
}
// Traverse the mappings graph using Tarjan's algorithm
- (void)visitMapping:(RKMapping *)mapping atKeyPath:(NSString *)keyPath
{
NSValue *dictionaryKey = [NSValue valueWithNonretainedObject:mapping];
if ([self.lowValues objectForKey:dictionaryKey]) {
if (![ mapping isKindOfClass:[RKEntityMapping class]]) return;
NSArray *keyPathComponents = [[self.visitationStack valueForKey:@"keyPath"] arrayByAddingObject:keyPath];
NSString *keyPath = [[keyPathComponents subarrayWithRange:NSMakeRange(1, [keyPathComponents count] - 1)] componentsJoinedByString:@"."];
RKMappingGraphVisitation *cyclicVisitation = [self visitationForMapping:mapping atKeyPath:keyPath];
cyclicVisitation.cyclic = YES;
[self.visitations addObject:cyclicVisitation];
return;
}
NSNumber *lowValue = @([self.lowValues count]);
[self.lowValues setObject:lowValue forKey:dictionaryKey];
NSUInteger stackPosition = [self.visitationStack count];
RKMappingGraphVisitation *visitation = [self visitationForMapping:mapping atKeyPath:keyPath];
[self.visitationStack addObject:visitation];
if ([mapping isKindOfClass:[RKObjectMapping class]]) {
RKObjectMapping *objectMapping = (RKObjectMapping *)mapping;
for (RKRelationshipMapping *relationshipMapping in objectMapping.relationshipMappings) {
[self visitMapping:relationshipMapping.mapping atKeyPath:relationshipMapping.destinationKeyPath];
// We want the minimum value
NSValue *relationshipKey = [NSValue valueWithNonretainedObject:relationshipMapping.mapping];
NSNumber *relationshipLowValue = [self.lowValues objectForKey:relationshipKey];
if ([lowValue compare:relationshipLowValue] == NSOrderedDescending) {
[self.lowValues setObject:relationshipLowValue forKey:dictionaryKey];
}
}
} else if ([mapping isKindOfClass:[RKDynamicMapping class]]) {
// Pop the visitation stack to remove the dynamic mapping, since each mapping within the dynamic mapping
// is rooted at the same point in the graph
[self.visitationStack removeLastObject];
for (RKMapping *nestedMapping in [(RKDynamicMapping *)mapping objectMappings]) {
[self visitMapping:nestedMapping atKeyPath:keyPath];
}
}
if ([[self.lowValues objectForKey:dictionaryKey] isEqualToNumber:lowValue]) {
NSRange range = NSMakeRange(stackPosition, [self.visitationStack count] - stackPosition);
NSArray *visitations = [self.visitationStack subarrayWithRange:range];
[self.visitationStack removeObjectsInRange:range];
// Take everything left on the stack
NSArray *keyPathComponents = [self.visitationStack valueForKey:@"keyPath"];
NSString *nestingKeyPath = ([keyPathComponents count] > 1) ? [[keyPathComponents subarrayWithRange:NSMakeRange(1, [keyPathComponents count] - 1)] componentsJoinedByString:@"."] : nil;
[visitations enumerateObjectsUsingBlock:^(RKMappingGraphVisitation *visitation, NSUInteger idx, BOOL *stop) {
// If this is an entity mapping, collect the complete key path
if ([visitation.mapping isKindOfClass:[RKEntityMapping class]]) {
visitation.keyPath = nestingKeyPath ? [@[ nestingKeyPath, visitation.keyPath ] componentsJoinedByString:@"."] : visitation.keyPath;
[self.visitations addObject:visitation];
}
// Update the low value
NSValue *relationshipKey = [NSValue valueWithNonretainedObject:mapping];
[self.lowValues setObject:self.numberOfDecriptors forKey:relationshipKey];
}];
}
}
@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;
}
/**
Traverses a set of cyclic key paths within the mapping result. Because these relationships are cyclic, we continue collecting managed objects and traversing until the values returned by the key path are a complete subset of all objects already in the set.
*/
static void RKAddObjectsInGraphWithCyclicKeyPathsToMutableSet(id graph, NSSet *cyclicKeyPaths, NSMutableSet *mutableSet)
{
if ([graph respondsToSelector:@selector(count)] && [graph count] == 0) return;
for (NSString *cyclicKeyPath in cyclicKeyPaths) {
NSSet *objectsAtCyclicKeyPath = RKFlattenCollectionToSet([graph valueForKeyPath:cyclicKeyPath]);
if ([objectsAtCyclicKeyPath count] == 0 || [objectsAtCyclicKeyPath isEqualToSet:[NSSet setWithObject:[NSNull null]]]) continue;
if (! [objectsAtCyclicKeyPath isSubsetOfSet:mutableSet]) {
[mutableSet unionSet:objectsAtCyclicKeyPath];
for (id nestedValue in objectsAtCyclicKeyPath) {
RKAddObjectsInGraphWithCyclicKeyPathsToMutableSet(nestedValue, cyclicKeyPaths, mutableSet);
}
}
}
}
/**
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'
*/
NSOrderedSet *RKSetByRemovingSubkeypathsFromSet(NSSet *setOfKeyPaths);
NSOrderedSet *RKSetByRemovingSubkeypathsFromSet(NSSet *setOfKeyPaths)
{
NSSet *prunedSet = [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;
}];
NSMutableOrderedSet *orderedSet = [NSMutableOrderedSet orderedSetWithSet:prunedSet];
if ([orderedSet containsObject:[NSNull null]]) {
[orderedSet removeObject:[NSNull null]];
[orderedSet setObject:[NSNull null] atIndex:0];
}
return orderedSet;
}
static void RKSetMappedValueForKeyPathInDictionary(id value, id rootKey, NSString *keyPath, NSMutableDictionary *dictionary)
{
NSCParameterAssert(value);
NSCParameterAssert(rootKey);
NSCParameterAssert(dictionary);
if (keyPath && ![keyPath isEqual:[NSNull null]]) {
id valueAtRootKey = [dictionary objectForKey:rootKey];
[valueAtRootKey setValue:value forKeyPath:keyPath];
} else {
[dictionary setObject:value forKey:rootKey];
}
}
// Precondition: Must be called from within the correct context
static NSManagedObject *RKRefetchManagedObjectInContext(NSManagedObject *managedObject, NSManagedObjectContext *managedObjectContext)
{
NSManagedObjectID *managedObjectID = [managedObject objectID];
if (! [managedObject managedObjectContext]) return nil; // Object has been deleted
if ([managedObjectID isTemporaryID]) {
RKLogWarning(@"Unable to refetch managed object %@: the object has a temporary managed object ID.", managedObject);
return managedObject;
}
NSError *error = nil;
NSManagedObject *refetchedObject = [managedObjectContext existingObjectWithID:managedObjectID error:&error];
NSCAssert(refetchedObject, @"Failed to find existing object with ID %@ in context %@: %@", managedObjectID, managedObjectContext, error);
return refetchedObject;
}
// Finds the key paths for all entity mappings in the graph whose parent objects are not other managed objects
static NSDictionary *RKDictionaryFromDictionaryWithManagedObjectsInVisitationsRefetchedInContext(NSDictionary *dictionaryOfManagedObjects, NSArray *visitations, NSManagedObjectContext *managedObjectContext)
{
if (! [dictionaryOfManagedObjects count]) return dictionaryOfManagedObjects;
NSMutableDictionary *newDictionary = [dictionaryOfManagedObjects mutableCopy];
[managedObjectContext performBlockAndWait:^{
NSSet *rootKeys = [NSSet setWithArray:[visitations valueForKey:@"rootKey"]];
for (id rootKey in rootKeys) {
NSSet *keyPaths = [NSSet setWithArray:[visitations valueForKey:@"keyPath"]];
NSOrderedSet *nonNestedKeyPaths = RKSetByRemovingSubkeypathsFromSet(keyPaths);
NSDictionary *mappingResultsAtRootKey = [dictionaryOfManagedObjects objectForKey:rootKey];
for (NSString *keyPath in nonNestedKeyPaths) {
__block BOOL refetched = NO;
if (! [keyPath isEqual:[NSNull null]]) {
if ([mappingResultsAtRootKey conformsToProtocol:@protocol(NSFastEnumeration)]) {
// This is a collection
BOOL respondsToSelector = YES;
for (id object in mappingResultsAtRootKey) {
if (! [object respondsToSelector:NSSelectorFromString(keyPath)]) respondsToSelector = NO;
}
if (! respondsToSelector) continue;
} else {
if (! [mappingResultsAtRootKey respondsToSelector:NSSelectorFromString(keyPath)]) {
continue;
}
}
}
id value = [keyPath isEqual:[NSNull null]] ? mappingResultsAtRootKey : [mappingResultsAtRootKey valueForKeyPath:keyPath];
if (! value) {
continue;
} else if ([value isKindOfClass:[NSArray class]]) {
BOOL isMutable = [value isKindOfClass:[NSMutableArray class]];
NSMutableArray *newValue = [[NSMutableArray alloc] initWithCapacity:[value count]];
for (__strong id object in value) {
if ([object isKindOfClass:[NSManagedObject class]]) {
object = RKRefetchManagedObjectInContext(object, managedObjectContext);
refetched = YES;
}
if (object) [newValue addObject:object];
}
value = (isMutable) ? newValue : [newValue copy];
} else if ([value isKindOfClass:[NSSet class]]) {
BOOL isMutable = [value isKindOfClass:[NSMutableSet class]];
NSMutableSet *newValue = [[NSMutableSet alloc] initWithCapacity:[value count]];
for (__strong id object in value) {
if ([object isKindOfClass:[NSManagedObject class]]) {
object = RKRefetchManagedObjectInContext(object, managedObjectContext);
refetched = YES;
}
if (object) [newValue addObject:object];
}
value = (isMutable) ? newValue : [newValue copy];
} else if ([value isKindOfClass:[NSOrderedSet class]]) {
BOOL isMutable = [value isKindOfClass:[NSMutableOrderedSet class]];
NSMutableOrderedSet *newValue = [NSMutableOrderedSet orderedSet];
[(NSOrderedSet *)value enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
if ([object isKindOfClass:[NSManagedObject class]]) {
object = RKRefetchManagedObjectInContext(object, managedObjectContext);
refetched = YES;
}
if (object) [newValue setObject:object atIndex:index];
}];
value = (isMutable) ? newValue : [newValue copy];
} else if ([value isKindOfClass:[NSManagedObject class]]) {
value = RKRefetchManagedObjectInContext(value, managedObjectContext);
refetched = YES;
}
if (value) {
RKSetMappedValueForKeyPathInDictionary(value, rootKey, keyPath, newDictionary);
// If we have refetched the root object, then we are done
if (keyPath == [NSNull null] && refetched) {
break;
}
}
}
}
}];
return newDictionary;
}
static NSURL *RKRelativeURLFromURLAndResponseDescriptors(NSURL *URL, NSArray *responseDescriptors)
{
NSCParameterAssert(URL);
NSCParameterAssert(responseDescriptors);
NSArray *baseURLs = [responseDescriptors valueForKeyPath:@"@distinctUnionOfObjects.baseURL"];
if ([baseURLs count] == 1) {
NSURL *baseURL = [baseURLs objectAtIndex:0];
NSString *pathAndQueryString = RKPathAndQueryStringFromURLRelativeToURL(URL, baseURL);
URL = [NSURL URLWithString:pathAndQueryString relativeToURL:baseURL];
}
return URL;
}
@interface RKManagedObjectRequestOperation ()
// Core Data specific
@property (nonatomic, strong) NSManagedObjectContext *privateContext;
@property (nonatomic, copy) NSManagedObjectID *targetObjectID;
@property (nonatomic, strong) RKManagedObjectResponseMapperOperation *responseMapperOperation;
@property (nonatomic, strong, readwrite) NSError *error;
@property (nonatomic, strong, readwrite) RKMappingResult *mappingResult;
@property (nonatomic, copy) id (^willMapDeserializedResponseBlock)(id deserializedResponseBody);
@end
@implementation RKManagedObjectRequestOperation
@dynamic willMapDeserializedResponseBlock;
// Designated initializer
- (id)initWithHTTPRequestOperation:(RKHTTPRequestOperation *)requestOperation responseDescriptors:(NSArray *)responseDescriptors
{
self = [super initWithHTTPRequestOperation:requestOperation responseDescriptors:responseDescriptors];
if (self) {
self.savesToPersistentStore = YES;
self.deletesOrphanedObjects = YES;
}
return self;
}
- (void)setTargetObject:(id)targetObject
{
[super setTargetObject:targetObject];
if ([targetObject isKindOfClass:[NSManagedObject class]]) {
self.targetObjectID = [targetObject objectID];
}
}
- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
_managedObjectContext = managedObjectContext;
if (managedObjectContext) {
// Create a private context
NSManagedObjectContext *privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[privateContext performBlockAndWait:^{
privateContext.parentContext = managedObjectContext;
privateContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy;
}];
self.privateContext = privateContext;
} else {
self.privateContext = nil;
}
}
#pragma mark - RKObjectRequestOperation Overrides
- (void)cancel
{
[super cancel];
[self.responseMapperOperation cancel];
}
- (RKMappingResult *)performMappingOnResponse:(NSError **)error
{
if (self.HTTPRequestOperation.wasNotModified) {
RKLogDebug(@"Managed object mapping requested for cached response: skipping mapping...");
NSURL *URL = RKRelativeURLFromURLAndResponseDescriptors(self.HTTPRequestOperation.response.URL, self.responseDescriptors);
NSArray *fetchRequests = RKArrayOfFetchRequestFromBlocksWithURL(self.fetchRequestBlocks, URL);
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);
}
}
}];
return [[RKMappingResult alloc] initWithDictionary:@{ [NSNull null]: managedObjects }];
}
self.responseMapperOperation = [[RKManagedObjectResponseMapperOperation alloc] initWithResponse:self.HTTPRequestOperation.response
data:self.HTTPRequestOperation.responseData
responseDescriptors:self.responseDescriptors];
self.responseMapperOperation.mapperDelegate = self;
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]];
[[RKObjectRequestOperation responseMappingQueue] addOperation:self.responseMapperOperation];
[self.responseMapperOperation waitUntilFinished];
if ([self isCancelled]) return nil;
if (self.responseMapperOperation.error) {
if (error) *error = self.responseMapperOperation.error;
return nil;
}
return self.responseMapperOperation.mappingResult;
}
- (BOOL)deleteTargetObjectIfAppropriate:(NSError **)error
{
__block BOOL _blockSuccess = YES;
if (self.targetObjectID
&& NSLocationInRange(self.HTTPRequestOperation.response.statusCode, RKStatusCodeRangeForClass(RKStatusCodeClassSuccessful))
&& [[[self.HTTPRequestOperation.request HTTPMethod] uppercaseString] isEqualToString:@"DELETE"]) {
// 2xx 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 *)localObjectsFromFetchRequestsMatchingRequestURL:(NSError **)error
{
NSMutableSet *localObjects = [NSMutableSet set];
__block NSError *_blockError;
__block NSArray *_blockObjects;
// Pass the fetch request blocks a relative `NSURL` object if possible
NSURL *URL = RKRelativeURLFromURLAndResponseDescriptors(self.HTTPRequestOperation.response.URL, self.responseDescriptors);
for (RKFetchRequestBlock fetchRequestBlock in [self.fetchRequestBlocks reverseObjectEnumerator]) {
NSFetchRequest *fetchRequest = fetchRequestBlock(URL);
if (fetchRequest) {
RKLogDebug(@"Found fetch request matching URL '%@': %@", URL, fetchRequest);
[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 '%@': %@", URL, fetchRequest, _blockObjects);
[localObjects addObjectsFromArray:_blockObjects];
} else {
RKLogDebug(@"Fetch request block %@ returned nil fetch request for URL: '%@'", fetchRequestBlock, URL);
}
}
return localObjects;
}
- (BOOL)deleteLocalObjectsMissingFromMappingResult:(RKMappingResult *)result withVisitor:(RKNestedManagedObjectKeyPathMappingGraphVisitor *)visitor 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.HTTPRequestOperation.wasNotModified) {
RKLogDebug(@"Skipping deletion of orphaned objects: 304 (Not Modified) status code encountered");
return YES;
}
// Build an aggregate collection of all the managed objects in the mapping result
NSMutableSet *managedObjectsInMappingResult = [NSMutableSet set];
NSDictionary *mappingResultDictionary = result.dictionary;
for (RKMappingGraphVisitation *visitation in visitor.visitations) {
id objectsAtRoot = [mappingResultDictionary objectForKey:visitation.rootKey];
id managedObjects = nil;
@try {
managedObjects = visitation.keyPath ? [objectsAtRoot valueForKeyPath:visitation.keyPath] : objectsAtRoot;
}
@catch (NSException *exception) {
if ([exception.name isEqualToString:NSUndefinedKeyException]) {
RKLogWarning(@"Caught undefined key exception for keyPath '%@' in mapping result: This likely indicates an ambiguous keyPath is used across response descriptor or dynamic mappings.", visitation.keyPath);
continue;
}
[exception raise];
}
[managedObjectsInMappingResult unionSet:RKFlattenCollectionToSet(managedObjects)];
if (visitation.isCyclic) {
NSSet *cyclicKeyPaths = [NSSet setWithArray:[visitation valueForKeyPath:@"mapping.relationshipMappings.destinationKeyPath"]];
[managedObjectsInMappingResult unionSet:RKFlattenCollectionToSet(managedObjects)];
RKAddObjectsInGraphWithCyclicKeyPathsToMutableSet(managedObjects, cyclicKeyPaths, managedObjectsInMappingResult);
}
}
NSSet *localObjects = [self localObjectsFromFetchRequestsMatchingRequestURL:error];
if (! localObjects) return NO;
RKLogDebug(@"Checking mappings result of %ld objects for %ld potentially orphaned local objects...", (long) [managedObjectsInMappingResult count], (long) [localObjects count]);
for (id object in localObjects) {
if (NO == [managedObjectsInMappingResult containsObject:object]) {
RKLogDebug(@"Deleting orphaned object %@: not found in result set and expected at this URL", object);
[self.privateContext performBlockAndWait:^{
[self.privateContext deleteObject:object];
}];
}
}
return YES;
}
- (BOOL)saveContext:(NSError **)error
{
__block BOOL success = YES;
__block NSError *localError = nil;
if ([self.privateContext hasChanges]) {
if (self.savesToPersistentStore) {
success = [self.privateContext saveToPersistentStore:&localError];
} else {
[self.privateContext performBlockAndWait:^{
success = [self.privateContext save:&localError];
}];
}
if (success) {
if ([self.targetObject isKindOfClass:[NSManagedObject class]]) {
[self.managedObjectContext performBlock:^{
RKLogDebug(@"Refreshing mapped target object %@ in context %@", self.targetObject, self.managedObjectContext);
[self.managedObjectContext refreshObject:self.targetObject mergeChanges:YES];
}];
}
} else {
if (error) *error = localError;
RKLogError(@"Failed saving managed object context %@ %@", (self.savesToPersistentStore ? @"to the persistent store" : @""), self.privateContext);
RKLogCoreDataError(localError);
}
}
return success;
}
- (BOOL)obtainPermanentObjectIDsForInsertedObjects:(NSError **)error
{
__block BOOL _blockSuccess = YES;
__block NSError *localError = nil;
NSArray *insertedObjects = [self.privateContext.insertedObjects allObjects];
if ([insertedObjects count] > 0) {
RKLogDebug(@"Obtaining permanent ID's for %ld managed objects", (unsigned long) [insertedObjects count]);
[self.privateContext performBlockAndWait:^{
_blockSuccess = [self.privateContext obtainPermanentIDsForObjects:insertedObjects error:&localError];
}];
if (!_blockSuccess && error) *error = localError;
}
return _blockSuccess;;
}
- (void)willFinish
{
BOOL success;
NSError *error = nil;
// Construct a set of key paths to all of the managed objects in the mapping result
RKNestedManagedObjectKeyPathMappingGraphVisitor *visitor = [[RKNestedManagedObjectKeyPathMappingGraphVisitor alloc] initWithResponseDescriptors:self.responseDescriptors];
// Handle any cleanup
success = [self deleteTargetObjectIfAppropriate:&error];
if (! success) {
self.error = error;
return;
}
success = [self deleteLocalObjectsMissingFromMappingResult:self.mappingResult withVisitor:visitor error:&error];
if (! success) {
self.error = error;
return;
}
// Persist our mapped objects
success = [self obtainPermanentObjectIDsForInsertedObjects:&error];
if (! success) {
self.error = error;
return;
}
success = [self saveContext:&error];
if (! success) self.error = error;
// Refetch all managed objects nested at key paths within the results dictionary before returning
if (self.mappingResult) {
NSDictionary *resultsDictionaryFromOriginalContext = RKDictionaryFromDictionaryWithManagedObjectsInVisitationsRefetchedInContext([self.mappingResult dictionary], visitor.visitations, self.managedObjectContext);
self.mappingResult = [[RKMappingResult alloc] initWithDictionary:resultsDictionaryFromOriginalContext];
}
}
@end