Last active
December 19, 2015 04:29
-
-
Save indragiek/5897899 to your computer and use it in GitHub Desktop.
Recursive Core Data saves with RAC. Works with nested contexts!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation NSManagedObjectContext (INAdditions) | |
- (RACSignal *)in_saveChanges | |
{ | |
return [[RACSignal startEagerlyWithScheduler:RACScheduler.scheduler block:^(id<RACSubscriber> subscriber) { | |
__block void (^recursiveBlock)(NSManagedObjectContext *); | |
recursiveBlock = [^(NSManagedObjectContext *context) { | |
[context performBlock:^{ | |
NSError *error = nil; | |
[context save:&error]; | |
// Not calling -sendError: at this point because we still want the | |
// parent contexts to be flushed in case they have any of their own | |
// changes that are not dependent on this save. | |
if (context.parentContext) { | |
#pragma clang diagnostic push | |
#pragma clang diagnostic ignored "-Warc-retain-cycles" | |
recursiveBlock(context.parentContext); | |
#pragma clang diagnostic pop | |
} else { | |
recursiveBlock = nil; | |
[subscriber sendCompleted]; | |
} | |
}]; | |
} copy]; | |
recursiveBlock(self); | |
}] deliverOn:RACScheduler.mainThreadScheduler]; | |
} | |
@end | |
// I use it for cool things like preventing app termination until a full save has completed: | |
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender | |
{ | |
[[_backgroundContext in_saveChanges] subscribeCompleted:^{ | |
[NSApp replyToApplicationShouldTerminate:YES]; | |
}]; | |
return NSTerminateLater; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment