I have the following code which is used on my View Controller whenever its property 'document' (of type UIManagedDocument
) is set.
I'm not sure if other people do, but I find the notion of concurrency in Core Data very confusing, the documents have a go at explaining it but it's still hard to get to grips with. For this reason, I was wondering if people had any ideas of how to speed up the code I use for saving the newly set UIDocument
if it does not exist. This code does work, if others would like to use it.
My main goal is to try and make the time it takes for the document to save and load much faster. It currently takes about 20 seconds to do this, which is way too long!
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
if (![[NSFileManager defaultManager] fileExistsAtPath:self.documentDatabase.fileURL.path]) {
[self.documentDatabase saveToURL:self.documentDatabase.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (success) {
NSLog(@"Saved %@", self.documentDatabase.localizedName);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.documentDatabase.managedObjectContext performBlockAndWait:^{
dispatch_async(dispatch_get_main_queue(), ^{
[Book newBookWithTitle:self.documentDatabase.fileURL.lastPathComponent.stringByDeletingPathExtension inManagedObjectContext:self.documentDatabase.managedObjectContext];
[self saveDocumentWithCompletionHandler:^(bool success) {
if (success) {
[self setIsDocumentHidden:NO];
}
}];
NSLog(@"Added default note to %@", self.documentDatabase.fileURL.lastPathComponent);
});
}];
});
} else {
NSLog(@"Error saving %@", self.documentDatabase.fileURL.lastPathComponent);
}
}];
} else {
[self openDocumentWithCompletionHandler:nil];
}